【发布时间】:2020-11-05 21:49:42
【问题描述】:
我有 Offer 和 OfferLocation。一个报价可以有多个报价位置。在保存报价时,我还想将报价位置保存到报价位置表中,但我收到一条错误消息:
“Microsoft.EntityFrameworkCore.DbUpdateException:更新条目时出错。有关详细信息,请参阅内部异常。\r\n ---> Microsoft.Data.SqlClient.SqlException (0x80131904):无法为标识插入显式值当 IDENTITY_INSERT 设置为 OFF 时,表“OfferLocation”中的列
请在下面找到代码:
public class Offer
{
public int Id { get; set; }
public virtual ICollection<OfferLocation> OfferLocations { get; set; }
...
}
public class OfferLocation
{
public int Id { get; set; }
public int OfferId { get; set; }
[ForeignKey("OfferId")]
public virtual Offer Offer { get; set; }
...
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<OfferLocation>().HasKey(od => new { od.Id, od.OfferId});
modelBuilder.Entity<OfferLocation>().HasOne(od => od.Offer).WithMany(od => od.OfferLocations).HasForeignKey(od => od.OfferId);
}
public class OfferRepository : BaseRepository<OfferModel>, IOfferRepository
{
public OfferRepository(Func<MMADbContext> contexFactory) : base(contexFactory) { }
public async Task<OfferModel> CreateAsync(OfferModel model)
{
var context = ContextFactory();
var offer = new Offer();
var offerLocations = new List<OfferLocation>();
context.Add(offer);
foreach (var location in model.Locations)
{
OfferLocation offerLocation = new OfferLocation();
offerLocation.Id = location.Id;
offerLocation.Country = location.Country;
offerLocation.Latitude = location.Latitude;
offerLocation.Longtitude = location.Longtitude;
offerLocation.Offer = offer;
offerLocation.Vicinity = location.Vicinity;
offerLocations.Add(offerLocation);
}
offer.OfferLocations = offerLocations;
await context.SaveChangesAsync();
return...
}
}
}
我知道问题与插入键和/或外键有关,但我知道如何解决它。任何帮助表示赞赏。
【问题讨论】:
-
由于这是一个 1:M 表并且 ID 实际上是 LocationID,
OfferLocation.ID应该不是IDENTITY。
标签: c# entity-framework entity-framework-core