0

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 !

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
zz32
  • 21
  • 1
  • Depends on the database - but typically, you must define a column as e.g. `INT IDENTITY` (in SQL Server or Oracle), or you need to define a **default constraint** for a column, for the RDBMS to automatically generate values on insert ... – marc_s Jan 22 '22 at 12:37
  • Isn't it done by default by EF Core ? – zz32 Jan 22 '22 at 19:58
  • @zz32 Since the `Id` in your Model `B` is a `Guid`, EF Core will not auto generate it by default, only the `int` Ids are auto generated by default. You have to tell EF Core explicitly to generate a `Guid` Id. Refer: https://stackoverflow.com/a/55935772/5260872 – Nishan Jan 24 '22 at 18:05
  • My `Guid` Ids are auto generated by EF Core in my other classes. – zz32 Jan 25 '22 at 23:04

0 Answers0