Entity Framework Code First - 不可为空类型的默认值
我正在尝试将旧数据库与旧 POCO 模型进行映射。由于开发数据库和模型时没有考虑实体框架,因此它们之间存在一些细微的差异,这让我陷入困境。
我面临的挑战是,我希望使其工作的侵入性尽可能小(不想接触数据库或模型的代码),因为依赖的代码太多。
我尝试使用代码优先方法来映射实体,重用遗留模型中的 POCO。自从我发现一些可为空的数字列被映射到声明为原始 Int32(不可为空)的属性以来,一切似乎都正常。
例如,假设我有一个 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; }
}
正如您可能会看到的,列 SomeNullableCol 和相应的属性之间存在差异,因为最后一个的类型是原始 int ,不允许空值。
是否有一种 hack 可以使此映射工作,而不必将 SomeNullableCol 的类型更改为可为空的 int (我的意思是 Int32?),并且如果可能的话,不触及该类的代码。
谢谢!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的,只需用数据注释掩盖它即可。创建一个可为 null 的 int 并将其掩码为列名称,然后创建一个具有相同名称的非映射属性,该属性仅从可为 null 的列返回 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.
你能让 POCO 上的属性可以为空吗?
Can you make the property on your POCO nullable?