2013-10-14 55 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