1
votes

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!

2

2 Answers

2
votes

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

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