实体框架中的自定义值类型

时间:2014-08-27 20:08:44

标签: c# entity-framework enums

我想在Entity Framework中使用自定义值类型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(enum的基类型)存储在数据库中。自定义值类型的目的是从映射到枚举值的字典中检索字符串值。当我首先在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
    }
}

1 个答案:

答案 0 :(得分:1)

这个问题的答案是通过注释或Fluent API将类视为复杂类型,添加带有枚举类型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