Hi
I have two viewmodels
public class modelA { public int Id {get;set;} public virtual modelB child {get;set;} } public class modelB { public int Id {get;set;} public virtual modelA parent {get;set;} } var viewModel = new modelA{ Id = 1, child = new modelB {Id = 2}}
now I have a partial view in which I put in modelB, the child, but I can’t access model A, what am I missing.
It simply says parent is null.
You haven’t set the parent property to anything so it is null
var viewModel = new modelA{ Id = 1, child = new modelB {Id = 2}} viewModel.child.parent = viewModel;
I guess the EF is making me lazy, since its already done with entity models, I was hoping it would be done automatically.
Can I just confirm your example will only have 2 models in memory and is fairly efficient?
modelA will have a list of modelBs, and I need them all to have a list to reference, so I plan to put the list in modelA and reference it from modelB, is this a good idea?
ModelB doesn’t have a parent defined. It would be automatically populated if you were using EF, but you aren’t in the example above so you need to set it manually:
var a = new modelA{ Id = 1}; var b = new modelB {Id = 2, parent = a}; a.child = b; var viewModel = a;
Note: Navigational Properties are purely an Entity Framework pattern.
Thanks both for the info, so If I have a list of modelB’s and in model be that needs to access a list of strings, is it better to put the list of strings in modelA and reference it with a naviagation property or put a list in each modelB?
I’m not clear what your model looks like, but I think I would do the following:
public class MyViewModel { public List<ModelB> ModelBs {get;set;} public List<string> StringsToReference {get;set;} }
Or does that miss something?
public class ModelA { public int Id {get;set;} public List<SelectListItem> SomeList {get;set;} public List<ModelB> Children {get;set;} } public class ModelB { public int Id {get;set;} public ModelA Parent {get;set;} public string SomeValue { get { return Parent.SomeList.Where(t => t.Value = "1").FirstOrDefault().Text;} }
or
public class ModelA { public int Id {get;set;} public List<ModelB> Children {get;set;} } public class ModelB { public int Id {get;set;} public List<SelectListItem> SomeList {get;set;} }
I know it modelA gets more complicated then it changes but based on this simple example I assuming the first option is better, to know for sure would be better.