ADO.Net - 将表char列映射到枚举

时间:2014-03-07 12:49:09

标签: entity-framework ado.net enumeration

在现有SQL表中,nvarchar列包含枚举信息。

我现在尝试使用枚举类来使用ADO.Net Entity Framework映射此列。但不知何故,这似乎不可能,因为它需要一个整数列。

ADO EF是否不支持映射到char列的枚举,或者如何实现它允许查询时使用linq或lambda语法?

错误:Given element assignment is invalid.

我更习惯于在很容易的情况下休眠。

1 个答案:

答案 0 :(得分:1)

您可以在模型中使用私有属性将数据映射到所需的任何属性类型。

// Model
public class Piece
{

    // Subclass Piece to add mappings for private properties
    public class PieceConfig : EntityTypeConfiguration<Piece>
    {
        public PieceConfig()
        {
            Property(b => b.dbtype); // needed for EF to see the private property
        }
    }

    [Column("type", TypeName = "VARCHAR")]
    private string dbtype { get; set; }

    [NotMapped]
    public PIECE type
    {
        get { return (PIECE)Enum.Parse(typeof(PIECE), dbtype); }
        set { dbtype= value.ToString(); }
    }
}

然后您只需要将配置添加到OnModelCreating方法

modelBuilder.Configurations.Add(new Piece.PieceConfig());
相关问题