我正在使用 EF Code-First 到现有数据库 方法并有一个 IsActive
我的数据库中的字段。问题是该字段是VARCHAR
什么时候应该是 boolean
.我无法更改数据库架构。
数据库中的示例值为“Y” (真)或“N” (假)
映射时,我想将这些值转换为真/假,并将我的实体类保留为 bool 值。
这可能吗?
我的实体和映射类如下,但我想更改 IsActive
字段为 bool 值。
public class Employee
{
public int ID { get; set; }
public string SSN { get; set; }
public string Email { get; set; }
public string IsActive { get; set; }
}
public class EmployeeMap : EntityTypeConfiguration<Employee>
{
public EmployeeMap()
{
this.ToTable("Employees");
this.HasKey(t => t.ID);
this.Property(t => t.ID).HasColumnName("ID_Employee");
this.Property(t => t.SSN).HasColumnName("sReference");
this.Property(t => t.Email).HasColumnName("Email");
this.Property(t => t.IsActive).HasColumnName("IsActive");
}
}
编辑:我没有找到除此之外的其他解决方案:https://stackoverflow.com/a/6709186/1053611
最佳答案
正如其他人指出的那样,您需要两个属性,但您可能有兴趣知道您可以将其中一个属性设为私有(private)并仍将其映射到数据库:
private string isActive { get; set; }
[System.ComponentModel.DataAnnotations.Schema.NotMapped]
public bool IsActive
{
get { return isActive == "Y"; }
set { isActive = value ? "Y" : "N"; }
}
如果您使用的是 EF6,您可以在
OnModelCreating
中使用自定义约定。映射私有(private)属性的方法modelBuilder.Types().Configure(c =>
{
//NB the syntax used here will do this for all entities with a
//private isActive property
var properties = c.ClrType.GetProperties(BindingFlags.NonPublic
| BindingFlags.Instance)
.Where(p => p.Name == "isActive");
foreach (var p in properties)
c.Property(p).HasColumnName("IsActive");
});
引用:
Mapping private properties using custom conventions
Mapping private properties without custom conventions (before EF6)
编辑:
这是识别应映射到数据库的私有(private)属性的另一种方法:
首先将 column 属性添加到私有(private)属性中:
[System.ComponentModel.DataAnnotations.Schema.Column]
private string isActive { get; set; }
然后使用该属性的存在来识别您的
OnModelCreating
中的私有(private)属性。方法:modelBuilder.Types().Configure(c =>
{
var properties = c.ClrType
.GetProperties(BindingFlags.NonPublic | BindingFlags.Instance)
.Where(propInfo =>
propInfo.GetCustomAttributes(typeof(ColumnAttribute), true).Length > 0);
foreach (var p in properties)
c.Property(p).HasColumnName(p.Name);
});
引用:Mapping a private property with entity framework
关于entity-framework - 映射时转换值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19370104/