Entity Framework 6 Code First - Custom Type Mapping

前端 未结 1 1663
迷失自我
迷失自我 2021-01-05 16:35

I\'m using some models inside my domain which are not very serialization- or mapping-friendly, such as structs or classes from the System.Net.* namespace.

相关标签:
1条回答
  • 2021-01-05 17:02

    wrap a NotMapped property of type PhysicalAddress with a mapped string property that handles the conversions:

        [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;
        }
    

    Update: example code for comment asking about wrapping functionality in a class

    [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;
        }
    }
    
    0 讨论(0)
提交回复
热议问题