MVC,不处理实体对象以便您可以使用它来深入了解外键值是一种不好的做法吗?
我是 MVC 新手。 在我浏览过的教程中,他们说最好的做法是在将实体对象传递到视图后将其处理掉。就像这样...
using(MyProjectEntities db = new MyProjectEntities)
{
return View(db.PersonAddresses.ToList());
}
但是我不想只显示 PersonAddress 表中链接的 Person 的 ID 和地址记录。我想要整个 shebang,但在我看来执行以下操作时出现错误。
<% foreach (var item in Model) { %>
<tr>
<td>
<%: item.Person.LastName + ", " + item.Person.FirstName %>
</td>
<td>
<%: item.Address.AddressLine1+ "<br />" + item.Address.AddressLine2 %>
</td>
<td>
<%: item.Room.RoomName %>
</td>
<td>
<%: String.Format("{0:g}", item.Date) %>
</td>
</tr>
<% } %>
但是,如果
MyProjectEntities db = new MyProjectEntities;
return View(db.PersonAddresses.ToList());
我的观点工作正常。
是否有更好的方法将这些值传递到视图,以便我可以正确处理实体对象?
I'm new to MVC.
In the tutorials I've gone through they say it is good practise to have your entities object disposed of after it is passed to the view. Like so...
using(MyProjectEntities db = new MyProjectEntities)
{
return View(db.PersonAddresses.ToList());
}
However I don't want to just display the IDs of the Person and the Address records that are linked in the PersonAddress table. I want the whole shebang and I get an error when I do the following in my view.
<% foreach (var item in Model) { %>
<tr>
<td>
<%: item.Person.LastName + ", " + item.Person.FirstName %>
</td>
<td>
<%: item.Address.AddressLine1+ "<br />" + item.Address.AddressLine2 %>
</td>
<td>
<%: item.Room.RoomName %>
</td>
<td>
<%: String.Format("{0:g}", item.Date) %>
</td>
</tr>
<% } %>
However if do
MyProjectEntities db = new MyProjectEntities;
return View(db.PersonAddresses.ToList());
My view works fine.
Is there a better way of passing those values to the view where I can dispose of the Entities object properly?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
一种方法是通过添加 .Include 来“急切”加载数据您的 LINQ 查询,这会预加载指定的数据,以便准备就绪。
One way is to "eager" load the data by adding .Include in your LINQ query, this pre-loads the specified data so it is ready to go.
最好不要直接从控制器访问数据层。我将创建一个单独的业务逻辑层或服务层,并从控制器调用它,而不是从控制器调用数据访问层。因此,您的数据访问层不会由用户界面层直接访问。那么这个问题就没有意义了。
It's better not to access your data layer directly from your controllers. I would create a separate business logic layer or service layer, and call that from the controllers, instead of calling the data access layer from your controllers. So your data access layer is not directly accessed by your user interface layer. This issue would then be moot.