I have 2 classes:
public class A
{
public int Id { get; set; }
public B BOne { get; set; }
public B BTwo { get; set; }
}
public class B
{
public Guid Id { get; set; }
public string MyField { get; set; }
}
Here is my EF Core config:
modelBuilder.Entity<A>(builder =>
{
builder.HasOne(a => a.BOne)
.WithMany()
.OnDelete(DeleteBehavior.Restrict);
builder.HasOne(a => a.BTwo)
.WithMany()
.OnDelete(DeleteBehavior.Restrict);
});
And I'm trying to add data like that:
var a = new A
{
BOne = new B
{
MyField = "One"
},
BTwo = new B
{
MyField = "Two"
},
};
context.Entry(a).State = await context.Set<T>().AnyAsync(_ => _.Id == a.Id)
? EntityState.Modified
: EntityState.Added;
await context.SaveChangesAsync();
Then I get this exception:
The INSERT statement conflicted with the FOREIGN KEY constraint "FK_A_B_BTwoId". The conflict occurred in database "db", table "dbo.B", column 'Id'.
I don't understand then problem, isn't EF Core generating the ids automatically when adding the data ?
Thanks !