MVC/EF 基础知识 - 如何从 MVC/EF 中的混合表/对象返回值?
我对 MS MVC 相当陌生 - 到目前为止,我已经创建了基本模板基础项目(主页和关于页面)并使用 EF 连接到我们现有的数据库。该应用程序是一个基本的调查应用程序。
在数据库中,每个调查记录都有一个带有 GUID 的 CreatedBy 列。该 GUID 映射回我们的登录数据库表,它是成员的用户 ID。
好的,所以使用 VS 内置的脚手架,我为我们使用的每个主要对象创建了控制器,包括登录和调查对象。脚手架在 SurveyController 中创建了一个 Index(),它看起来像这样:
public ViewResult Index()
{
return View(db.Surveys.ToList());
}
当我运行应用程序时,所有内容都列出得非常好,但在 CreatedBy 列中是一个又大又难看的 GUID。这不是很有帮助,我真的想显示与该 GUID 关联的实际成员的名称。
实现这一目标的最佳方法是什么?我考虑过更改 Survey 对象,添加 LoginName 字段并填充该字段,但这会“破坏”代码,如果我想稍后更新脚手架,我将丢失在这里所做的任何更改。
我确信这是一个常见问题。我想知道返回视图时是否有组合跨表/跨对象数据的最佳实践?
I am fairly new to MS MVC - so far I have created the basic template base project (Home and About pages) and used EF to hook up to our existing DB. The application is a basic survey application.
In the database, each survey record has a CreatedBy column with a GUID. That GUID maps back to our Logins database table, it is the UserID of the member.
OK, so using the scaffolding built into VS, I created controller for each main object we work with, including the Login and Survey objects. The scaffolding created an Index() in the SurveyController, it looks like this:
public ViewResult Index()
{
return View(db.Surveys.ToList());
}
When I run the app, everything lists very nice, but in the CreatedBy column is a big ugly GUID. This isn't very helpful, I really want to show the name of the actual member associated with that GUID.
What is the best way to accomplish this? I thought about altering the Survey object, adding a LoginName field, and populating that, but that "breaks" the code in that, if I want to update the scaffolding later, I will lose any changes I make here.
I'm sure this is a common issue. I'm wondering if there is a best practice to combine cross-table/cross-object data when returning a View?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我个人(未经 MSFT 批准)的建议是始终尝试使用“代码优先”,并尽可能远离 ObjectContext。即使您有现有数据库,您仍然可以通过 使用强大的工具对数据库进行逆向工程(仍在 CTP1 中)。更具体地说,这个问题以及您在不久的将来可能遇到的许多问题可能会在 MSDN 上的教程。我们(EF 团队)与 ASP.NET MVC 团队密切合作,确保这些教程是高质量的,而且听起来正是您所需要的。请务必查看左侧导航栏以获得良好的起点。
My personal (non-MSFT-approved) advice is to consistently try to use "Code First" and to stay away from ObjectContext if at all possible. Even if you have an existing database, you can still use Code First by reverse engineering the database with the power tools (still in CTP1). More specifically, this question and many of the questions you are likely to encounter in the near future are likely to be answered in the tutorials on MSDN. We (the EF team) worked closedly with the ASP.NET MVC team to make sure these tutorials are high quality, and it sounds like exactly what you need. Make sure to look in the left nav bar for a good starting point.