Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Entity Framework Auto-Update Property Navigation By Id

In Entity Framework, when I've mapped my tables to the corresponding entities through the designer and get to actually using them, I'll find that an entity - Thing, who has a relationship (many to one, or one to one) with another object, say, Bob, for example, would produce the following three properties on Thing:

Bob
BobId
BobReference

And were I to set BobId, and save my entity, the next time I fetch this Thing, I'll be able to navigate the Bob property without trouble. I'm curious, however, if it is possible to configure EF to allow me to navigate the property without having to immediately save.

like image 619
CassOnMars Avatar asked Mar 26 '26 11:03

CassOnMars


1 Answers

You can do something like this: (EF 4.1)

//Has to exists a record on Bob table with Id = 1
var thing = new Thing() { BobId = 1 };

var context = new YouContext();
context.Entry(thing ).State = EntityState.Unchanged;
context.Entry(thing ).Reference(x => x.Bob).Load();

and then thing.Bob is != null

like image 81
marianosz Avatar answered Mar 29 '26 00:03

marianosz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!