实体框架代码第一 - 非可空类型的默认值 [英] Entity Framework Code First - Default values on non-nullable types

查看:109
本文介绍了实体框架代码第一 - 非可空类型的默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用传统POCO模型映射遗留数据库。由于数据库和模型的发展并不在意实体框架,所以有一些小的区别,使我陷入困境。

i'm trying to map a legacy database with a legacy POCO model. Since database and model where develop not having in mind Entity Framework there are some little differences between that made me stuck.

我面临的挑战是我想使其工作尽可能少的侵害性(不想触摸数据库的代码和模型),因为有太多依赖的代码。

The challenge I'm facing is that I would like to make it work being as less invasive as possible (don't want to touch code of the database nor the model) since there is too much codes that depends on.

我尝试使用代码优先方法映射实体,重用旧版模型中的POCO。每个东西似乎都可以发现,因为我发现一些可空的数字列映射到被声明为原始Int32(不可空)的属性。

I have tried to map the entities using a code first approach, reusing the POCOs from the legacy model. Every thing seemed to work find since I found that some nullable numeric columns were mapped to properties that are declared as primitive Int32 (not nullable).

例如,假设我有一个表:

For example, let's say I have a table:

CREATE TABLE [dbo].[SomeTable](
    [Id] [int] NOT NULL,
    [Descrip] [nvarchar](50) NULL,
    [SomeNumericCol] [int] NULL,
 CONSTRAINT [PK_SomeTable] PRIMARY KEY CLUSTERED 
(
    [Id] ASC
)) ON [PRIMARY]

和相应的POCO:

public class SomeTable
{
    public Int32 Id { get; set; }
    public string Descrip { get; set; }
    public Int32 SomeNullableCol { get; set; }
}

您可能会看到列之间有区别Some 和相应的属性,因为last的类型是不允许空值的原始int。

As you might see there is a difference between the column SomeNullableCol and the corresponding property, since the type of the last is a primitive int which doesn't allow nulls.

是否有一个黑客使这个映射工作而不必将SomeNullableCol的类型更改为可空的int(我的意思是Int32?),如果可能,请勿触摸该类的代码。

Is there a hack to make this mapping work without having to change the type of SomeNullableCol to a nullable int (I mean Int32? ), and if possible not touching the code of the class.

谢谢! >

Thanks!

推荐答案

是的,只需用数据注释掩码即可。创建一个可空的int并将其屏蔽到列名称,然后创建一个具有相同名称的非映射属性,该属性只返回一个可从空的列中的int值。

Yes, just mask it with data annotations. Create a nullable int and mask it to the column name, then create a nonmapped property with that same name that only returns an int value from the nullable column.

        [Column("SomeNullableCol")]
        public int? TestValue { get; set; }

        [NotMapped]
        public int SomeNullableCol
        {
            set { TestValue = value; }
            get
            {
                if (TestValue != null) return (int) TestValue;
                return -1;
            }
        }

这篇关于实体框架代码第一 - 非可空类型的默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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