Customising Type Mappings in Entity Framework

2019-07-18 07:50发布

问题:

I'm using EF5 Code First and I'm trying to store an IPAddress object. If you try and do this directly, EF stores it as two columns, FIELDNAME_Address and FIELDNAME_Scope. Unfortunately, this is insufficient for storing IPv4 addresses, as accessing ScopeId throws an exception (see C# The attempted operation is not supported for the type of object referenced).

What I'd like to be able to do is define how a type gets mapped in EF, but I'm not sure how to do that, or what the terminology for it is. This would be the cleanest solution and allow my POCO to remain pure:

public class TestRecord 
{
    public int Id { get; set; }
    public IPAddress IP { get; set; }
}

With something in the OnModelCreating to describe how to serialize + unserialize an IPAddress object.

Another option I've considered is using a wrapper field:

public class TestRecord 
{
    public int Id { get; set; }
    public long value_ip { get; set; }
    [NotMapped]
    public IPAddress IP 
    { 
        get { return value_ip.ToIPAddress(); }
        set { value_ip = value.ToLong(); 
    } 
} 

Unfortunately, this either requires the field to be public, or some fiddling with expressions in order to map the private field. Either way, it's not as clean as being able to define at the Context level "this is how you store an IPAddress type", which is my preferred solution.

回答1:

EF has no support for serialization/deserializtion, custom type mapping or mapped type conversions. You must either use complex type and somehow handle it inside that type or you must use your wrapped field (complex type would use wrapped field as well).