我有一个具有char属性的对象:
public class Product
{
public char Code
{
get;
set;
}
}
实体框架似乎无法映射字符(当我从模型对象创建数据库模式时,数据库中缺少此字段)。无论如何我可以使用流畅的API映射char(例如字符串)吗?我不想更改模型对象,因为它们是遗留共享库的一部分。
Char
不是实体框架的有效原始类型=实体框架不映射它。如果你检查CSDL reference,你会看到有效类型的列表(char
不在其中)。
数据库char(1)
被翻译为string
(SQL to CSDL translation)。 Char
被描述为non-unicode string with fixed length 1。
唯一丑陋的选择是使用字符串的第二个映射属性,而你的char
非映射属性将只使用该属性中的string[0]
。这只是EF中一些简单类型映射或转换器丢失的另一个例子。
在Fluent API中,您可以使用HasColumnType方法指定数据库列数据类型,如下所示:
modelBuilder.Entity<Product>()
.Property(p => p.Code)
.HasColumnType("char");
根据Andre Artus的回答here,HasColumnType可以在EF4.1中找到。
对于那些使用Data Annotations的人来说,ColumnAttribute可以完成同样的事情。
[Column(TypeName="char")]
public string Code { get; set; }
我已经尝试了所有我想象的方法,并且我必须说接受的答案是解决char类型问题的独特方法,据我所知。
char类型不能在EntityFramework中使用。
Fluent API包含在此限制中。
如果你试图在Property(p => p.MyCharProperty)
上放一个字符会给你一个例外。
这意味着char属性不适用于Fluent API和Attributes。
最简单的解决方案就是这个(由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]; }
}
}
一个注意事项:您不能将该属性设为私有,受保护或内部。必须公开。
流畅的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)
有其他方法可以解决此问题仅用于测试目的。从设计模式开始,使该字段不为null。有时它受限于SQL Management Studio。 (更改设置工具 - >选项 - >设计器 - >表数据库设计器 - >取消选中“防止保存需要创建表的更改”