如何使用Entity Framework 4.1“仅代码”流畅的API映射char属性?

时间:2011-07-20 10:55:10

标签: entity-framework char ef4-code-only fluent-interface

我有一个具有char属性的对象:

public class Product
{
    public char Code
    {
        get;
        set;
    }
}

实体框架似乎无法映射字符(当我从模型对象创建数据库模式时,数据库中缺少此字段)。无论如何我可以使用流畅的API映射char(例如字符串)吗?我不想更改模型对象,因为它们是遗留共享库的一部分。

5 个答案:

答案 0 :(得分:68)

Char对于实体框架来说是无效的原始类型=实体框架不会映射它。如果您选中CSDL reference,则会看到有效类型列表(char不在其中)。

数据库char(1)被翻译为stringSQL to CSDL translation)。 Char被描述为non-unicode string with fixed length 1

唯一丑陋的选项是使用字符串的第二个映射属性,而您的char非映射属性将仅使用该属性中的string[0]。这只是EF中一些简单类型映射或转换器丢失的另一个例子。

答案 1 :(得分:29)

在Fluent API中,您可以使用HasColumnType方法指定数据库列数据类型,如下所示:

modelBuilder.Entity<Product>()   
.Property(p => p.Code)   
.HasColumnType("char");

根据Andre Artus的说法&#39;回答here,HasColumnType在EF4.1中可用。

对于那些使用数据注释的人来说,ColumnAttribute可以完成同样的事情。

[Column(TypeName="char")]
public string Code { get; set; }

答案 2 :(得分:1)

我已经尝试了所有我想像的方法,必须说接受的答案是据我所知解决字符类型问题的独特方法。

字符类型不能在EntityFramework中使用。

Fluent API包含在此限制中。

如果您尝试在Property(p => p.MyCharProperty)上放置字符,则会为您提供例外

这意味着 char 属性不适用于Fluent API或属性。

最简单的解决方法是此方法(由Ladislav Mrnka提出)。

public class Product
{
    public char Code { get; set; }

    [Column("Code", TypeName="char")]
    [MaxLength(1)]
    public string CodeString
    {
         get { return Code.ToString(); }
         set { Code = value[0]; }
    }
}

一个注意事项:您不能将其设置为私有,受保护或内部。 必须公开

Fluent API版本就是这样。

public class Product
{
    public char Code { get; set; }

    //We need the property but we will use the Fluent API to replace the attributes
    public string CodeString
    {
         get { return Code.ToString(); }
         set { Code = value[0]; }
    }
}

modelBuilder.Entity<Product>().Property(p => p.Code)
    .HasTypeName("char")
    .HasMaxLength(1)

答案 3 :(得分:1)

[Column( TypeName = "char(1)" )]

使用EF core 3.1.4为我工作

答案 4 :(得分:0)

还有其他方法可以仅出于“测试”目的解决此问题。使字段从设计模式暂时不为null变为null。有时它是受限制的SQL Management Studio。 (更改设置工具->选项->设计器->表数据库设计器->取消选中“防止保存需要创建表的更改”