在实体框架中自定义类型映射 [英] Customising Type Mappings in Entity Framework

查看:237
本文介绍了在实体框架中自定义类型映射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是EF5 Code First,我正在尝试存储一个IPAddress对象。如果您直接尝试并执行此操作,EF将其存储为FIELDNAME_Address和FIELDNAME_Scope两列。不幸的是,这不足以存储IPv4地址,因为访问ScopeId会引发异常(请参阅 C#对于对象类型不支持尝试的操作参考)。



我想要做的是定义如何在EF中映射类型,但我不知道如何这样做,或者是什么术语。这将是最干净的解决方案,并允许我的POCO保持纯净:

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

在OnModelCreating中有一些内容来描述如何序列化+ unserialize一个IPAddress对象。



我考虑过的另一个选项是使用包装器字段:

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

不幸的是,这要么将该字段公开,或者用一些表达方式来映射私人领域。无论哪种方式,它不像在Context级别定义的那样干净,这是你如何存储IPAddress类型,这是我的首选解决方案。

解决方案

EF具有不支持序列化/反序列化,自定义类型映射或映射类型转换。您必须使用复杂类型,并以某种方式处理该类型,或者您必须使用您的包装字段(复杂类型也将使用包装字段)。


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.

解决方案

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).

这篇关于在实体框架中自定义类型映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆