Sunday, 15 May 2011

entity framework - DbContext and navigation properties in EF 4.4 -



entity framework - DbContext and navigation properties in EF 4.4 -

after switching project entityobject generator dbcontext, ran issue using navigation properties on new objects. i've spent important amount of time researching problem, , i'm no closer desirable solution.

first, generated class definitions:

public partial class category { public category() { this.limits = new hashset<limit>(); } public int categoryid {get; set;} public string name {get; set;} public virtual icollection<limit> limits { internal get; set; } } public partial class limit { public int categoryid {get; set;} public string description {get; set;} internal virtual category category { get; set; } }

i creating test info during integration test using next code:

using (gfcamdatacontext db = new gfcamdatacontext()) { limit = new limit() { categoryid = testdata.categoryid, description = "signercontroller.update" }; db.limits.add(limit); db.savechanges(); }

without other changes, limit.category property of newly-created limit object not homecoming anything. however, if query desired category dbcontext before savechanges called navigation property on new limit starts returning associated category. objectcontext, category property updated without intervention me.

i have same behavior objectcontext, can't seem find way accomplish goal. i've seen couple of proposed solutions:

make navigation properties public. had same behavior, , isn't desirable public navigation properties can cause issues during serialization , aren't needed outside of business layer.

make properties public virtual , utilize dbset.create ensure proxy creation. resulted in same behavior, , isn't desirable have code dynamically creating instances (i.e. don't have access dbset @ time creating entity instance).

does have suggestions solution problem?

one solution explicitly load nested entity:

db.savechanges(); db.entry(person).reference(z => z.category).load();

the other option, when proxies enabled, indeed phone call dbset.create<t>(). if don't have access dbset instance @ time create entities, might want expose public method in repository interface allows that. example:

public interface irepository<t> { t add(t entity); t getbyid(...); void savechanges(); ... t createinstance(); // concrete implementation have access dbset , uses dbset.create<t>() }

entity-framework dbcontext

No comments:

Post a Comment