0

I'm running into a strange situation:

public Class A 
{
      public int Id { get; set; }
}

public class B 
{ 
     public int Id { get; set; }
     [ForeignKey("A1")]
     public virtual int A_Id { get; set; }
     public virtual A A1 { get; set; }
}

When I update an entity of type B, by modifying A1, A1.Id is updated to the new entity Id, but B.A_Id still remains assigned to the old Id. This causes Entity Framework to throw an error.

I had read that by marking both properties as virtual, EF change tracker would automatically detect the change and update the related foreign key, but this doesn't happen for me. What else can I check?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Riz
  • 6,486
  • 19
  • 66
  • 106

1 Answers1

0

How you map the relationship between A & B will determine the behavior. You do not need to mark the A_Id as Virtual.

Provided your real schema is mapped out like above, it should just work as a typical many-to-one mapping. (Many B's can reference an A) The Key point is that the A_Id on B will not be updated until you call SaveChanges on the DbContext. Once SaveChanges is called, the FK will be updated to reflect the different A.

For instance:

       using (var context = new TestDbContext())
        {
            var a = context.As.Single(x => x.Id == 1);
            var b = context.Bs.Single(x => x.Id == 1);
            Assert.AreEqual(2, b.A_id);
            b.A = a;
            context.SaveChanges();
            Assert.AreEqual(1, b.A_Id);
        }

When B was loaded it was referencing an A with ID = 2. We load A ID #1 and associate it to B using the reference. Once SaveChanges is called we can assert that B's A_Id now reflects the link to A ID 1.

Beyond that you may be encountering issues depending on how/where your A and B references are loaded. Ensure that they are coming from the same DbContext instance. A big problem I see people having is by passing references to entities around. This often leads to exceptions when trying to update references within the scope of a DbContext using entities that were loaded elsewhere.

If you are still running into issues or suspect something like above, include a copy of your exception message and actual code and we can take it from there.

Steve Py
  • 26,149
  • 3
  • 25
  • 43