更改SQL表设计,使用外键来建模类



我有3个表:

CREATE TABLE [dbo].tbl_emp (
emp_id INT PRIMARY KEY IDENTITY (1, 1),
emp_NAME nvarchar(max),
emp_CONTACT nvarchar(10)
);
CREATE TABLE [dbo].tbl_allowance (
allowance_id INT PRIMARY KEY IDENTITY (1, 1),
allowance_NAME nvarchar(max)
);
CREATE TABLE [dbo].tbl_emp_allowance (
emp_allowance_id INT PRIMARY KEY IDENTITY (1, 1),
emp_id nvarchar INT,
allowance_id INT 
);

以上这些示例表来自我们的web form项目。现在我们正在把这个项目转化为asp.net mvc 4应用。

我必须把这些表改成code first method。具有挑战性的部分是,我必须创建一个页面来为employee [emp_NAME, emp_CONTACT]插入数据,并且还应该有一个下拉菜单来为每个员工记录选择allowance_NAME。将会有另一个页面用于插入allowance信息。

我已经为两个表创建了类。

[Table("tbl_emp")]
public class EmpModel
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int emp_id { get; set; }
public string emp_NAME { get; set; }
public string emp_CONTACT { get; set; }
}

[Table("tbl_allowance")]
public class AllowanceModel
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int allowance_id { get; set; }
public string allowance_NAME { get; set; }
}

但是我在第三张桌子上有问题。在ASP中做这些事情的正确方法是什么?. NET MVC应用程序?

然后如何创建插入页,这样,数据应该插入到tbl_emptbl_emp_allowance

使用代码优先的方法绑定表:

[Table("tbl_emp")]
public class EmpModel
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int emp_id { get; set; }
public string emp_NAME { get; set; }
public string emp_CONTACT { get; set; }
public virtual List<ThirdModel> ThirdModel {get;set;}
}
[Table("tbl_allowance")]
public class AllowanceModel
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int allowance_id { get; set; }
public string allowance_NAME { get; set; }
public virtual List<ThirdModel> ThirdModel {get;set;}
}
[Table("third_table")]
public class ThirdModel
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int id { get; set; }
[ForeignKey("Employee")]
public int EmployeeID{ get; set; }
public virtual EmpModel Employee { get; set; }
[ForeignKey("Allowence")]
public int AllowenceID{ get; set; }
public virtual AllowenceModel Allowence { get; set; }

}
现在我们的第三个模型包含EmpModel和AllowenceModel。您可以从第三个模型访问这两个模型。

要使用一对多关系,只需使用

public virtual List<Model1> Model1 {get;set;} // many side
[ForeignKey("Model1")]
public int Model1ID{ get; set; }
public virtual Model1 Model1{ get; set; }// one side

最新更新