我通常通过 2 个“部分”课程来做到这一点。一种用于直接映射的数据库属性。一个用于额外的东西。
在一个名为 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);
}
}
}
请注意,我有一个只读(“get”)属性(“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()
{
// Primary Key
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);
// Table & Column Mappings
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);
}
}
}