Mvc代码第一款 [英] Mvc code first style

查看:152
本文介绍了Mvc代码第一款的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我做了一个简单的mvc 3网站。它的工作正常,但数据库和类是凌乱的,因为我需要做下拉列表,我不知道如何使用不同的样式来实现drowdownlists。



如:

  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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆