在上篇文章中"LINQ To SQL Discriminator Column Example - Inheritance Mapping Tutorial”,我可以很容易的改变Employee实体的EmployeeType属性为一个枚举EmployeeType,LINQ To Sql会自动去解决枚举和int之间的转换。
在数据库中EmployeeType字段是一个int类型:
我可以添加一个枚举类型,叫EmployeeType:
public enum EmployeeType : int
{
HourlyEmployee = 0,
SalariedEmployee = 1,
CommissionedEmployee = 2
}
{
HourlyEmployee = 0,
SalariedEmployee = 1,
CommissionedEmployee = 2
}
同时为继承映射改变鉴别器属性,用enum代替int:
[Column(Storage="_EmployeeType", DbType="Int NOT NULL",
CanBeNull=false, IsDiscriminator=true)]
public EmployeeType EmployeeType
{
//
}
CanBeNull=false, IsDiscriminator=true)]
public EmployeeType EmployeeType
{
//
}
它运行得很好,LINQ To SQL自己解决了它们之间映射。
理想情况下,也不需要直接在EmployeeType属性上做其他工作。你可以创建一个SalariedEmpoyee类:
using (HRDataContext dc = new HRDataContext())
{
Employee empNew = new SalariedEmployee();
empNew.Name = "Jane Doe";
dc.Employees.Add(empNew);
dc.SubmitChanges();
}
{
Employee empNew = new SalariedEmployee();
empNew.Name = "Jane Doe";
dc.Employees.Add(empNew);
dc.SubmitChanges();
}
或者像这样的其他的类,也可以隐藏如何创建合适的employee类型,而不需要一个EmplyeeFactory。(这句好像翻得有点晕,原文是:You may be hiding the creation of the proper employee type behind an EmployeeFactory, but you get the idea.)
直接枚举支持很爽,嘿嘿。