实体字段的可为空属性,实体框架通过代码优先 [英] Nullable property to entity field, Entity Framework through Code First

查看:46
本文介绍了实体字段的可为空属性,实体框架通过代码优先的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

像这样使用数据注解Required:

[Required]
public int somefield {get; set;}

将数据库中的somefield设置为Not Null,如何设置somefield是否允许 NULL?,我尝试通过 SQL Server Management Studio 进行设置,但实体框架将其设置回 Not Null.

Will set somefield to Not Null in database, How can I set somefield to allow NULLs?, I tried setting it through SQL Server Management Studio but Entity Framework set it back to Not Null.

推荐答案

只需省略 string somefield 属性中的 [Required] 属性.这将使它在数据库中创建一个 NULLable 列.

Just omit the [Required] attribute from the string somefield property. This will make it create a NULLable column in the db.

要使 int 类型在数据库中允许 NULL,它们必须在模型中声明为可空的 int:

To make int types allow NULLs in the database, they must be declared as nullable ints in the model:

// an int can never be null, so it will be created as NOT NULL in db
public int someintfield { get; set; }

// to have a nullable int, you need to declare it as an int?
// or as a System.Nullable<int>
public int? somenullableintfield { get; set; }
public System.Nullable<int> someothernullableintfield { get; set; }

这篇关于实体字段的可为空属性,实体框架通过代码优先的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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