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.
Remove the identiy of the
offerLocation.Id
column on database. You are trying to set an Identity to a primary key but you are not allowed to do it.
in this line
modelBuilder.Entity<OfferLocation>().HasKey(od => new { od.Id, od.OfferId});
you are trying to use composite primary key, but you need only (od => od.Id)
as id
is your only primary key
also
you don't need to use annotation [ForeignKey("OfferId")]
or even fluent api configurations in OnModelCreating
, as you already used "valid convention"
you can visit this link for more information about build relations with conventions
User contributions licensed under CC BY-SA 3.0