I have a code-first EF model like this:
public partial class A
{
[Key]
[StringLength(7)]
public string Code { get; set; }
[Required]
[StringLength(100)]
public string Name { get; set; }
public virtual ICollection<B> Bs { get; set; }
}
public partial class B
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[Required]
[StringLength(100)]
public string Name { get; set; }
[Required]
[StringLength(7)]
[ForeignKey("A")]
public string ACode { get; set; }
public virtual A A { get; set; }
}
When I am inserting data like this:
var a = new A();
a.Code = "A0";
a.Name = "A Name";
var b = new B();
b.Name = "B Name";
b.ACode = a.Code;
b.A = a;
using (DbContext context = new DbContext())
{
context.As.Add(a);
context.Bs.Add(b);
context.SaveChanges();
}
var b2 = new B();
b2.Name = "B Name 2";
b2.ACode = a.Code;
b2.A = a;
using (DbContext context = new DbContext())
{
context.Bs.Add(b2);
context.SaveChanges();
}
I have no problem during first context.SaveChanges
. But when I try to add b2 with same ACode
and reference I get
Violation of PRIMARY KEY constraint 'PK_dbo.As'. Cannot insert duplicate key in object 'dbo.As'. The duplicate key value is (A0 ).
I'm really confused about that do so I would be very glad if someone could explain why on the second call to context.SaveChanges()
, EF is trying to insert new A entity instead of using the already existing one.
Thank you very much for your help