entity framework - Loading preexisting navigation properties of new disconnected entities -


i have new disconnected poco (in case aspnet mvc modelbinder).

public class offlineentry {     public virtual int id { get; set; }     public virtual category category { get; set; }     public virtual int categoryid { get; set; } } 

the foreign key property (categoryid) set existing database value navigation reference (category) null @ first. right way load navigation reference? expect step 1 add new object context. before savechanges, can use lazy loading, or loadproperty, or have set manually?

public contentresult save(offlineentry o) {     db.offlineentries.add(o);     var categoryname = o.category.name; //?     db.savechanges();     return content("ok"); }  public class category {     public virtual int id { get; set; }     public virtual string name { get; set; }     //optional 2-way nav property } 

i hoping else jump on expert, 1 issue see you're going have instance of offlineentry not created dbcontext, , lazyloading isn't going work.

generally better practice not use entity models view models, being 1 of reasons.

so suggestion create newofflineentryviewmodel below:

public class newofflineentryviewmodel {     public int categoryid { get; set; } } 

and retrieve category dbcontext manually

public contentresult save(newofflineentryviewmodel model) {     var category = db.categories.find(model.categoryid);      var newentry = db.offlineentries.create();     db.offlineentries.add(newentry);     newentry.category = category;      db.savechanges();      var categoryname = category.name; //for whatever needed      return content("ok"); } 

Comments

Popular posts from this blog

android - getbluetoothservice() called with no bluetoothmanagercallback -

sql - ASP.NET SqlDataSource, like on SelectCommand -

ios - Undefined symbols for architecture armv7: "_OBJC_CLASS_$_SSZipArchive" -