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.