温馨提示:本文翻译自stackoverflow.com,查看原文请点击:其他 - Entity Framework Core Insert entry with relationship 1 to many

其他 - 具有多对多关系的Entity Framework Core Insert条目

发布于 2020-03-29 13:15:15

让我解释一下,我有2个表格:燃料和车辆。1辆车可以有更多加油口,一辆加油车有1辆车。因此,这是正常的1-M关系。

但是,当我尝试插入新的Fuel并选择已经存在的Vehicle时,这是一个例外:

Duplicate entry '5' for key 'vehicle.PRIMARY'

就像当我尝试创建一个新的Fuel条目,而不是将Fuel条目链接到现有的Vehicle时,它尝试创建一个新的。实际上,如果我使用后 map,而不是使用现有车辆,而是放置新 map,它会同时创建“燃料”和“车辆”条目。

这是我实际使用的代码:Fuel类:

public class Fuel
{
    [Key]
    public int id { get; set; }
    public DateTime date { get; set; }
    public float cost { get; set; }
    [ForeignKey("vehicleId")]
    public virtual Vehicle vehicle { get; set; }
    public int vehicleId { get; set; }
    public float startKm { get; set; }
    public float endKm { get; set; }
    public float liter { get; set; }
    public float average { get; set; }
}

车辆类别:

 public class Vehicle
{
    [Key]
    public int id { get; set; }
    [Required, MaxLength(7), MinLength(7)]
    public string plate { get; set; }
    [JsonIgnore, InverseProperty("vehicle")]
    public ICollection<Fuel> Fuels { get; set; } = new HashSet<Fuel>();
}

DatabaseContext:

protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<JourneyAddress>()
            .HasKey(bc => new { bc.journeyId, bc.addressId });
        modelBuilder.Entity<JourneyAddress>()
            .HasOne(bc => bc.journey)
            .WithMany(b => b.journeyAddress)
            .HasForeignKey(bc => bc.journeyId)
            .OnDelete(DeleteBehavior.Cascade);
        modelBuilder.Entity<JourneyAddress>()
            .HasOne(bc => bc.address)
            .WithMany(c => c.JourneyAddress)
            .HasForeignKey(bc => bc.addressId)
            .OnDelete(DeleteBehavior.Cascade);
        modelBuilder.Entity<Fuel>()
            .HasOne(c => c.vehicle)
            .WithMany(e => e.Fuels)
            .HasForeignKey(c => c.vehicleId)
            .OnDelete(DeleteBehavior.Cascade);
    }

控制器:

public async Task<ActionResult<Fuel>> PostFuel(Fuel fuel)
    {
        _repo.Add(fuel);
        var save = await _repo.SaveAsync(fuel);

        return CreatedAtAction("GetFuel", new { id = fuel.id }, fuel);
    }

现有车辆的
POSTMAP新车辆的POSTMAP

查看更多

查看更多

提问者
Fanto
被浏览
21
Fanto 2020-01-31 17:44

我已经通过使用此功能而不是旧功能解决了该问题:

Controller.cs

        public async Task<ActionResult<Fuel>> PostFuel(Fuel fuel)
    {
        var vehicle = _context.Vehicle.SingleOrDefault(t => t.id == fuel.vehicleId);
        fuel.vehicle = vehicle;
        _repo.Add(fuel);
        var save = await _repo.SaveAsync(fuel);

        return CreatedAtAction("GetFuel", new { id = fuel.id }, fuel);
    }

发布
问题

分享
好友

手机
浏览

扫码手机浏览