我往往通过使用两个“局部”类来实现此目的。一个用于直接映射数据库属性,另一个用于额外的内容。
在名为 Employee.cs 的文件中。
public partial class Employee
{
public Employee()
{
}
public System.Guid EmployeeUUID { get; set; }
public string SSN { get; set; }
public string LastName { get; set; }
public string FirstName { get; set; }
public System.DateTime ? CreateDate { get; set; }
public System.DateTime HireDate { get; set; }
}
然后在一个名为EmployeeExtended.cs的文件中。
public partial class Employee
{
public string EmployeeFullName
{
get
{
return string.Format("{0}, {1} ('{2}')", this.LastName, this.FirstName, this.SSN);
}
}
}
请注意,上面的代码中有一个只读属性(“EmployeeFullName”),它与EF兼容并且不需要任何更改即可正常工作。
我还可以这样做:
public partial class Employee
{
public string EmployeeFullName
{
get
{
return string.Format("{0}, {1} ('{2}')", this.LastName, this.FirstName, this.SSN);
}
}
public string SomeNonTrackedDatabaseProperty { get; set; }
}
但是我需要在“SomeNonTrackedDatabaseProperty”的映射中添加“.Ignore”,因为它不是数据库中的列。
public class EmployeeMap : EntityTypeConfiguration<Employee>
{
public EmployeeMap()
{
this.HasKey(t => t.EmployeeUUID);
this.Property(t => t.SSN)
.IsRequired()
.HasMaxLength(11);
this.Property(t => t.LastName)
.IsRequired()
.HasMaxLength(64);
this.Property(t => t.FirstName)
.IsRequired()
.HasMaxLength(64);
this.ToTable("Employee");
this.Property(t => t.EmployeeUUID).HasColumnName("EmployeeUUID");
this.Property(t => t.SSN).HasColumnName("SSN");
this.Property(t => t.LastName).HasColumnName("LastName");
this.Property(t => t.FirstName).HasColumnName("FirstName");
this.Property(t => t.CreateDate).HasColumnName("CreateDate");
this.Property(t => t.HireDate).HasColumnName("HireDate");
this.Ignore(t => t.SomeNonTrackedDatabaseProperty);
}
}
}
StudentNameFormatter
类,它公开了一个StudentNamePlusALetter()
方法(向其中传递一个Student
和一个string
)。 - 48klocs