2012-10-16 58 views
-1

我是新约MVC + EF将数据插入多个表MVC3

我需要在一个时间数据插入到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; } 
    } 

任何人都可以告诉我怎么看这个模型的控制器和视图文件?

+0

您是否尝试过除上述之外的其他任何事情? –

+0

您可以使用存储过程在一个过程执行中将数据插入到3个表中。 – 2012-10-16 08:02:07

回答

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

0

我必须创建新的类,其中将包括所有这些类是这样的:

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

而且你必须回到这个模型的回报视图(视图模型),并创造出比你可以绑定像这样的表强烈tiped观点:

foreach(var item in ViewModel.LoginModel) 
{ 

}