I am running into an interesting issue when trying to add an entity to the database with Entity Framework. When I try to add a new exception to the database, I run into the following error:
"Cannot insert explicit value for identity column in table 'Notification' when identity_insert is set to off"
I am guessing this error is caused due to the Notification entity already having an Identifier (Id property). However, my goal is not to store the Notification entity. It just so happens that my NotificationException entity has a reference to an existing Notification entity.
How can I update my NotificationException entities properly without running into this problem? Actually turning the identity_insert off does not seem like a viable solution.
My two model classes:
public class Notification
{
// Primary Key
public long Id { get; set; }
// Properties
public bool IsSent { get; set; }
public bool IsExpired { get; set; }
public int RetryCount { get; set; }
public int RetryTime { get; set; }
}
public class NotificationException
{
// Primary Key
public long Id { get; set; }
// Properties
public int Timestamp { get; set; }
public string Exception { get; set; }
// Foreign Keys
public long NotificationId { get; set; }
// Navigation Properties
public virtual Notification Notification { get; set; }
}
Entity Configuration with Fluent API:
private void ConfigureNotificationEntity(EntityTypeBuilder<Notification> builder)
{
builder.ToTable("Notifications");
builder.HasKey(i => i.Id);
builder.Property(i => i.Id)
.IsRequired()
.ValueGeneratedOnAdd();
builder.HasMany(n => n.Exceptions)
.WithOne(e => e.Notification)
.OnDelete(DeleteBehavior.Cascade);
}
private void ConfigureNotificationExceptionEntity(EntityTypeBuilder<NotificationException> builder)
{
builder.ToTable("NotificationExceptions");
builder.HasKey(i => i.Id);
builder.Property(i => i.Id)
.IsRequired()
.ValueGeneratedOnAdd();
builder.HasOne(i => i.Notification)
.WithMany(j => j.Exceptions);
}
The main problem:
public async Task<NotificationException> Add (NotificationException item)
{
_context.NotificationExceptions.Add(item);
await _context.SaveChangesAsync();
return item;
}
As soon as the _context.SaveChangesAsync(); is called, the error mentioned above is thrown.
///Edit
I tested this issue with different objects as well. If the entity has no nested entities, then storing them works just fine. The issue is quite likely with the already known ID of the nested entity.
idinNotificationException item