Acr*_*gma 6 c# database entity-framework
我在我的域中使用了一些不是非常序列化或映射友好的模型,例如System.Net.*命名空间中的结构或类.
现在我想知道是否可以在Entity Framework中定义自定义类型映射.
伪:
public class PhysicalAddressMap : ComplexType<PhysicalAddress>() {
public PhysicalAddressMap() {
this.Map(x => new { x.ToString(":") });
this.From(x => PhysicalAddress.Parse(x));
}
}
Run Code Online (Sandbox Code Playgroud)
期望的结果:
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)
Run Code Online (Sandbox Code Playgroud)
使用处理转换的映射字符串属性包装NotMapped类型的PhysicalAddress属性:
[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;
}
Run Code Online (Sandbox Code Playgroud)
更新:用于评论关于在类中包装功能的注释的示例代码
[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;
}
}
Run Code Online (Sandbox Code Playgroud)