I have Offer and OfferLocation. One offer can have many offer location. While saving offer I also want to save offer locations into offer location table, but I get an error saying:
"Microsoft.EntityFrameworkCore.DbUpdateException: An error occurred while updating the entries. See the inner exception for details.\r\n ---> Microsoft.Data.SqlClient.SqlException (0x80131904): Cannot insert explicit value for identity column in table 'OfferLocation' when IDENTITY_INSERT is set to OFF
Please find code below:
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...
}
}
}
I know that the problem has to do with inserting key and/or foreign key, but I know sure how to so solve it. Any help appreciated.
OfferLocation.ID
should not be anIDENTITY
. – Panagiotis Kanavos Jul 16 '20 at 9:02