Entity Framework 6 Code First - 自定义类型映射

7
我正在使用一些在序列化或映射方面不太友好的模型,比如来自System.Net.*命名空间的结构体或类。现在我想知道是否可以在Entity Framework中定义自定义类型映射。
public class PhysicalAddressMap : ComplexType<PhysicalAddress>() {
    public PhysicalAddressMap() {

        this.Map(x => new { x.ToString(":") });
        this.From(x => PhysicalAddress.Parse(x));
    }
}

期望结果:

SomeEntityId       SomeProp         PhysicalAddress    SomeProp
------------------------------------------------------------------
           4          blubb       00:00:00:C0:FF:EE        blah

                                           ^
                                           |
                             // PhysicalAddress got mapped as "string"
                             // and will be retrieved by
                             // PhysicalAddress.Parse(string value)
1个回答

9
将类型为PhysicalAddressNotMapped属性包装为映射的字符串属性,并处理转换:
    [Column("PhysicalAddress")]
    [MaxLength(17)]
    public string PhysicalAddressString
    {
        get
        {
            return PhysicalAddress.ToString();
        }
        set
        {
            PhysicalAddress = System.Net.NetworkInformation.PhysicalAddress.Parse( value );
        }
    }

    [NotMapped]
    public System.Net.NetworkInformation.PhysicalAddress PhysicalAddress
    {
        get;
        set;
    }

更新:针对询问如何将功能封装在类中的评论提供示例代码。
[ComplexType]
public class WrappedPhysicalAddress
{
    [MaxLength( 17 )]
    public string PhysicalAddressString
    {
        get
        {
            return PhysicalAddress == null ? null : PhysicalAddress.ToString();
        }
        set
        {
            PhysicalAddress = value == null ? null : System.Net.NetworkInformation.PhysicalAddress.Parse( value );
        }
    }

    [NotMapped]
    public System.Net.NetworkInformation.PhysicalAddress PhysicalAddress
    {
        get;
        set;
    }

    public static implicit operator string( WrappedPhysicalAddress target )
    {
        return target.ToString();
    }

    public static implicit operator System.Net.NetworkInformation.PhysicalAddress( WrappedPhysicalAddress target )
    {
        return target.PhysicalAddress;
    }

    public static implicit operator WrappedPhysicalAddress( string target )
    {
        return new WrappedPhysicalAddress() 
        { 
            PhysicalAddressString = target 
        };
    }

    public static implicit operator WrappedPhysicalAddress( System.Net.NetworkInformation.PhysicalAddress target )
    {
        return new WrappedPhysicalAddress()
        {
            PhysicalAddress = target
        };
    }

    public override string ToString()
    {
        return PhysicalAddressString;
    }
}

有没有办法将这种行为封装在一个类中以便重用? - billy
当然可以 - 创建一个带有相关转换运算符的复杂类型。将示例代码添加到解决方案中。 - Moho
好的,谢谢。我现在遇到的问题是,由于向后兼容性,我无法重命名数据库列,所以我想将类型为WrappedPhysicalAddress的每个属性映射到自定义列。 - billy
用属性吗?(我不喜欢流畅的API) - billy
3
几乎不支持任何EF表达式树。 - Aron
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接