2013-10-14 56 views
33

我正在使用EF代码 - 首先到现有数据库方法并在我的数据库中有IsActive字段。问题是该字段为VARCHAR,应该是boolean。我无法更改数据库模式。在数据库映射时转换值

示范值是 “Y” (真)或 “N” (假)

当映射,我希望将这些值转换为true/false,并让我的实体类与布尔值

这可能吗?

我的实体和映射类如下,但我想将IsActive字段更改为布尔值。

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

+0

您使用首先从数据库反向工程,对吧?所以你的班级员工是自动生成和部分? –

+0

是的,正确的,但我手动映射它们。 – Gaui

+0

对不起,我将EF Code-First用于现有数据库。 – Gaui

回答

37

正如其他人所指出的,你需要两个属性,但你可能有兴趣知道,你可以让民营的属性之一并且它仍然映射到数据库:

private string isActive { get; set; } 

    [System.ComponentModel.DataAnnotations.Schema.NotMapped] 
    public bool IsActive 
    { 
     get { return isActive == "Y"; } 
     set { isActive = value ? "Y" : "N"; } 
    } 

如果您正在使用EF6可以在OnModelCreating方法使用自定义的约定来映射私有财产

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)

编辑:

这里的确定应被映射到数据库中的私人性质的另一种方式:

一列属性添加到私有财产:

[System.ComponentModel.DataAnnotations.Schema.Column] 
private string isActive { get; set; } 

然后使用该属性的存在在你的OnModelCreating方法来确定私有属性:

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

+1

谢谢。知道我可以映射一个私有财产突然为我节省了大量的代码。 – ProfK

+6

这不会阻止你用'where x.IsActive'之类的东西写数据库的LINQ查询,因为公共属性不会被映射? – Mykroft

+2

@Mycroft是的,它会的。但是,如果将所有数据访问代码保存在单独的程序集中,则可以考虑将属性设置为“内部”而不是“私有”。 – Colin