[英]MVC 5 one to many virtual ICollection returning null?
I have a model which looks like this 我有一个看起来像这样的模型
public class MyModel
{
....
public virtual ICollection<Comm_ent> Comments { get; set; }
}
and the submodels look like 子模型看起来像
public class Comm_ent
{
...
public virtual My_Model MyModel{ get;set;}
}
In my Comm_ent Datatable
I have a MyModelId
key created by migration but when I do 在我的
Comm_ent Datatable
我有一个通过迁移创建的MyModelId
密钥,但是当我这样做时
public actionresult MyModelIndex(int? id)
{
var mymodel = _context.MyModels.singleordefault(u => u.Id == id)
return View(mymodel);
}
The @Model.Comments
is null
even though I have entries in Comm_ent datatable
. 即使我在
Comm_ent datatable
有条目, @Model.Comments
为null
。 This was working in MVC4 but after upgrade to MVC5 it returns null result. 这在MVC4中有效,但升级到MVC5后返回空结果。 Any ideas how to do this in MVC5?
任何想法如何在MVC5中执行此操作?
Try to add Include
method: 尝试添加
Include
方法:
public actionresult MyModelIndex(int? id)
{
var mymodel = _context.MyModels.Include(u => u.Comments).singleordefault(u => u.Id == id)
return View(mymodel);
}
Don't forget to add the following using
statement: 不要忘记添加以下
using
语句:
using System.Data.Entity;
Try initializing the collection in the constructor for MyModel: 尝试在MyModel的构造函数中初始化集合:
public MyModel(){
Comments = new HashSet<Comm_ent>();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.