将数据插入多个表MVC3

时间:2012-10-16 07:54:48

标签: c# asp.net-mvc-3

我是关于MVC + EF的新手

我需要一次将数据插入3个表中,但无法弄清楚我该怎么做 我的数据模型是

public class UserLogin
    {
        [Key]public int UserID { get; set; }
        public string LoginName { get; set; }
        public byte Password { get; set; }
    }
    public class UserDetails
    {
        [Key]
        public int DetailID { get; set; }
        [ForeignKey("UserLogin")]
        public int UserID { get; set; }
        public string UserName { get; set; }
        public string Address { get; set; }
    }
    public class UserType
    {
        [Key]
        public int TypeID { get; set; }
        [ForeignKey("UserLogin")]
        public int UserID { get; set; }
        public string TypeName { get; set; }
        public string TypeDiscription { get; set; }
    }
    public class UserBDCon : DbContext
    {
        public DbSet<UserLogin> logins { get; set; }
        public DbSet<UserDetails> Detail { get; set; }
        public DbSet<UserType> Type { get; set; }
    }

有谁能告诉我如何查看该模型的控制器和视图文件?

2 个答案:

答案 0 :(得分:0)

我必须创建一个包含所有这些类的新类:

public class ViewModel()
{
   public IList<UserLogin> LoginModel {get; set;}
   public IList<UserDetails> DetailsModel {get; set;}
   public IList<UserType> TypeModel {get; set;}
}

你必须返回这个模型返回View(ViewModel)并创建强大的tiped视图,而不是像这样绑定表:

foreach(var item in ViewModel.LoginModel)
{

}

答案 1 :(得分:0)

您应该在模型类中创建其他属性:

数据模型应该是这样的:

public class UserLogin
{
    [Key]
    public int UserID { get; set; }
    public string LoginName { get; set; }
    public byte Password { get; set; }
}
public class UserDetails
{
    [Key]
    public int DetailID { get; set; }

    [ForeignKey("UserLogin")]
    public int UserID { get; set; }

    public string UserName { get; set; }
    public string Address { get; set; }

    //additional
    public UserLogin UserLogin { get; set; }
}
public class UserType
{
    [Key]
    public int TypeID { get; set; }
    [ForeignKey("UserLogin")]
    public int UserID { get; set; }
    public string TypeName { get; set; }
    public string TypeDiscription { get; set; }

    //additional
    public UserLogin UserLogin { get; set; }
}

示例(没有工作单元和存储库,但是单个上下文):

    UserBDCon db = new UserBDCon();

    var userLogin = new UserLogin() {LoginName = "Admin", Password = new byte()};
    var details = new UserDetails() {Address = "Address", UserName = "Admin", UserLogin = userLogin};
    var type = new UserType() {TypeDiscription = "Description", TypeName = "TypeName", UserLogin = userLogin};

    db.logins.Add(userLogin);
    db.Detail.Add(details);
    db.Type.Add(type);

    db.SaveChanges(); // EF insert data into 3 table at a time

您应该使用相同的数据库上下文。在这种情况下,查询将是同一事务的一部分。 更好地实现目标单一事务的存储库模式和工作单元,如http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/implementing-the-repository-and-unit-of-work-patterns-in-an-asp-net-mvc-application