实体框架中的自定义值类型
本文关键字:类型 自定义 框架 实体 | 更新日期: 2023-09-27 18:19:35
我想使用这里详细介绍的自定义值类型http://vbcity.com/blogs/jatkinson/archive/2010/01/12/create-custom-types-and-initialize-them-without-the-new-keyword-c-vb-net.aspx]实体框架中的1。它们的底层类型是一个枚举,所以我想把整个东西作为枚举的基类型int存储在数据库中。自定义值类型的用途是从映射到枚举值的字典中检索字符串值。当我首先在EF代码中使用自定义值类型作为实体的属性时,不会生成数据库列。此外,当使用EF电动工具查看模型时,该属性不会显示。
这是我的自定义值类型:
public struct AttachmentType
{
private AttachmentType(AttachmentTypeCode attachmentTypeCode)
{
if (CodesValues.ContainsKey(attachmentTypeCode))
{
_val = attachmentTypeCode;
}
else
{
throw new InvalidEnumArgumentException("This is not a valid attachment type code.");
}
}
public override string ToString()
{
return CodesValues[_val];
}
private AttachmentTypeCode _val;
public static implicit operator AttachmentType(AttachmentTypeCode attachmentTypeCode)
{
return new AttachmentType(attachmentTypeCode);
}
private static readonly Dictionary<AttachmentTypeCode, string> CodesValues = new Dictionary<AttachmentTypeCode, string>()
{
{AttachmentTypeCode.Email, "Electronic Mail Message"},
{AttachmentTypeCode.WordDocument, "Microsoft Word 2007 Document"},
{AttachmentTypeCode.PDF, "Adobe PDF Document"},
};
public enum AttachmentTypeCode
{
Email= 1,
WordDocument= 2,
PDF = 3
}
}
这个问题的答案是通过annotation或Fluent API将类视为复杂类型,使用enum类型的getter添加公共属性以访问内部私有属性,并添加一个自定义的代码优先配置,如下所示,将刚刚创建的复杂类型的公共属性(在我的情况下是枚举,EF5支持)映射到数据库字段:
modelBuilder.Types<ClassAttachmentTypeIsUsedIn>()
.Configure(ctc => ctc.Property(cust => cust.AttachmentType.EnumProperty)
.HasColumnName("AttachmentType"));
点击此处查看更多信息:http://visualstudiomagazine.com/articles/2014/04/01/making-complex-types-useful.aspx