Entity Framework Code First - Default values on non-nullable types

一世执手 提交于 2019-12-25 03:37:15

问题


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.

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]

and the corresponding POCO:

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

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.

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!


回答1:


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;
            }
        }



回答2:


Can you make the property on your POCO nullable?

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


来源:https://stackoverflow.com/questions/7941472/entity-framework-code-first-default-values-on-non-nullable-types

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!