实体框架6代码优先-自定义类型映射

本文关键字:自定义 类型 映射 框架 代码 实体 | 更新日期: 2023-09-27 17:52:44

我正在使用域内的一些模型,这些模型不是很序列化或映射友好,例如来自System.Net.*命名空间的结构体或类。

现在我想知道是否有可能在实体框架中定义自定义类型映射。

伪:

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)

实体框架6代码优先-自定义类型映射

将类型为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;
    }
}