Mvc代码第一款 [英] Mvc code first style
问题描述
如:
public class Departments
{
public int ID {get; set;}
...
}
public class Users
{
public int ID {get; set;}
...
public Department Dept {get; set;}
public List< Department> DeptList {get; set;}
public string SelectedDept {get; set;}
}
然后我使用DropDownListFor帮助。我是新的代码第一件事,可悲的是。所以,现在我在数据库中有两个不必要的列。任何其他方式做这个更清洁/更好?
你的课程应该像这样
code> public class Users
{
public int ID {get; set;}
...
public virtual int DeptId {get; set;}
[ForeignKey(DeptId)]
public virtual Department Dept {get; set;}
}
然后在您执行的MVC .NET控制器中一个查询来填充List DeptList。
DeptList可以存储在ViewBag.DeptList中,或者作为返回到视图的Model的属性。
string不需要SelectedDept。当您使用DropDownListFor Helper时,它将自动为您设置Users.DeptId。
此外,您可能需要考虑将Users重命名为User=)
I made a simple mvc 3 web site. It's working fine but the database and classes are messy because I needed to make dropdownlists and I have no idea how to implement the drowdownlists using a different style.
Here's how things look like:
public class Departments
{
public int ID {get; set;}
...
}
public class Users
{
public int ID {get; set;}
...
public Department Dept {get; set;}
public List<Department> DeptList {get; set;}
public string SelectedDept {get; set;}
}
then I used DropDownListFor helper. I'm new on this code first thing, sadly. So, now I got these 2 extra unnecessary columns along in the database. Any other way to do this cleaner/better?
Your class should look like this
public class Users
{
public int ID {get; set;}
...
public virtual int DeptId {get; set;}
[ForeignKey("DeptId")]
public virtual Department Dept {get; set;}
}
Then in your MVC .NET Controller you perform a query to populate List DeptList. DeptList can be stored in ViewBag.DeptList or as a property of the Model you return to the view.
string SelectedDept is not needed. When you use DropDownListFor helper it will automatically set Users.DeptId for you.
Also you may want to consider renaming "Users" to "User" =)
这篇关于Mvc代码第一款的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!