简体   繁体   English

实体框架代码优先-DbNull约定

[英]Entity Framework Code First - DbNull Convention

My problem is I have an existing table that I can not modify that contains fields that are nullable. 我的问题是我有一个无法修改的现有表,其中包含可为空的字段。

I have a model that I do not want nullable properties. 我有一个我不希望可为空的属性的模型。

What I want to do is have a convention (I presume this is how) where I can set the default value to use based on the models property type when DBNull is encountered from the database. 我想要做的是有一个约定(我想是这样),在该约定中,当从数据库中遇到DBNull时,可以基于models属性类型设置要使用的默认值

  • ints/double = 0 整数/双精度= 0
  • string = "" 字符串=“”
  • bool = false 布尔=错误

Pretty sure this was simple to do in NHibernate but I can't find out how to do this in EF. 可以肯定的是,这在NHibernate中很容易实现,但是我找不到在EF中如何做到这一点。

I am using the latest EF package from nuget which I believe is EF 4.2. 我正在使用nuget的最新EF软件包,我相信它是EF 4.2。

It is not possible because EF doesn't support custom conventions (unless you hack them in). 这是不可能的,因为EF不支持自定义约定(除非您侵入了它们)。 Moreover even with conventions it would probably not work. 而且,即使有约定,它也可能行不通。

What you are looking for is custom simple type mapping (or simple type conversion). 您正在寻找的是自定义简单类型映射(或简单类型转换)。 It is very important feature of ORM but till now it is completely ignored in EF. 这是ORM的非常重要的功能,但到目前为止,它在EF中已被完全忽略。 Currently DB type should match your type in EF model otherwise you can have serious problems because you cannot do any conversion inside mapping. 当前,数据库类型应与EF模型中的类型匹配,否则可能会出现严重问题,因为您无法在映射内部进行任何转换。 The first conversion will be supported in EF 5 and it will only support converting int to enum (hardcoded conversion). EF 5将支持第一次转换,它将仅支持将int转换为枚举(硬编码转换)。

In EF nullable type in database => nullable type in your model. 在数据库中的EF可空类型=>模型中的可空类型中。

As alentranks hints at above, this could possibly be handled using some magic with Nullable<T> properties. 正如上面的alentranks所暗示的那样,可以使用具有Nullable<T>属性的一些魔术来处理此问题。 In my experience Nullable<T> doesn't handle DBNull on its own (though I could be wrong), you could use a trick defined here : 以我的经验, Nullable<T>不能独自处理DBNull (尽管我可能是错的),您可以使用此处定义的技巧:

private static T NullValue<T>( object testValue, T nullValue )
{
    T returnValue;
    if( testValue is DBNull )
    {
        returnValue = nullValue;
    }
    else if( typeof(T).GetGenericTypeDefinition().Equals( typeof(Nullable<>) ) )
    {
        returnValue = (T)Convert.ChangeType( testValue, Nullable.GetUnderlyingType( typeof(T) ) );
    }
    else
    {
        returnValue = (T)Convert.ChangeType( testValue, typeof(T) );
    }

    return returnValue;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM