实体设计中的外键关系

时间:2011-01-25 23:46:56

标签: c# linq-to-sql

我有这两个实体。一个针对员工:

[Table(Name = "Employees")]
public class Employee
{
    [HiddenInput(DisplayValue = false)]
    [Column(IsPrimaryKey = true, IsDbGenerated = true, AutoSync = AutoSync.OnInsert)]
    public int UserID { get; set; }

    [Column]
    [Required(ErrorMessage = "Please enter a first name")]
    [DisplayName("First Name")]
    public string FirstName { get; set; }

    [Column]
    [DisplayName("Last Name")]
    [Required(ErrorMessage = "Please enter a last name")]
    public string LastName { get; set; }

    [Column]
    [DisplayName("Department")]
    [Required(ErrorMessage = "Please select a department")]
    public int DepartmentID { get; set; }
}

还有一个部门:

[Table(Name = "Departments")]
public class Department
{
    [HiddenInput(DisplayValue = false)]
    [Column(IsPrimaryKey = true, IsDbGenerated = true, AutoSync = AutoSync.OnInsert)]
    public int DepartmentID { get; set; }

    [Column]
    [Required(ErrorMessage = "Please enter a department name")]
    public string Name { get; set; }
}

在我的数据库中,我在DepartmentID上的这两个表之间有一个外键关系。但在我的实体类中,我没有任何指定这一点。

我是否需要在这些类中添加内容?

1 个答案:

答案 0 :(得分:2)

为什么要手动生成实体类? (为什么你不使用sqlmetal.exe和/或.dbml文件?)手写类不是可行的方法,因为当错误是如何定义实体时,LinqToSql提供真正可怕的异常消息。

但要回答你的问题,是的,你错过了[Association]属性。 (sqlmetal.exe将为您生成。)如果没有这个,您就不能轻易编写跨表/关系操作的LINQ查询。

类似的东西:

[Column]
[DisplayName("Department")]
[Required(ErrorMessage = "Please select a department")]
public int DepartmentID { get; set; }

private EntityRef<Department> department;

[Association(IsForeignKey = true, ThisKey = "DepartmentId"]
public Department Department 
{ 
    get { return department.Entity; }
    set { department.Entity = value; }
}

现在您可以编写类似于以下内容的查询:

db.Employees.Where(x => x.Department.Name == "Accounting");

但是,真的不应该手动执行此操作。