39

我将EF Code-First 用于现有的数据库方法,并IsActive在我的数据库中有一个字段。问题是该字段VARCHAR何时应该是boolean. 我无法更改数据库架构。

数据库中的示例值为“Y” (真)或“N” (假)

映射时,我想将这些值转换为 true/false 并将我的 Entity 类保留为boolean value

这可能吗?

我的实体和映射类如下,但我想将该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

4

2 回答 2

47

正如其他人指出的那样,您需要两个属性,但您可能有兴趣知道您可以将其中一个属性设为私有并仍将其映射到数据库:

    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");
});

参考:

使用自定义约定映射私有属性

在没有自定义约定的情况下映射私有属性(在 EF6 之前)

编辑:

这是识别应映射到数据库的私有属性的另一种方法:

首先将 column 属性添加到私有属性中:

[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);
});

参考:使用实体框架映射私有属性

于 2013-10-15T09:04:47.017 回答
-2

我有一个解决方案来实际映射类型,这意味着不需要其他属性。因为我对 DateTimes 有类似的问题,但很容易转换为 bool:

是否有一种简单的方法使用数据注释或自定义类型将存储为 SQL 中的字符串的值用作 EF 中的 DateTime?

于 2018-08-23T10:25:35.667 回答