Required
像这样使用数据注释:
[Required]
public int somefield {get; set;}
将设置somefield到Not Null
数据库中,如何设置somefield
允许空值?我试图通过SQL Server Management Studio,但实体框架的设置将其设置回Not Null
。
Answers:
只需从string somefield
属性中省略[Required]属性。这将使它NULL
在数据库中创建一个有能力的列。
为了使int类型在数据库中允许NULL,必须在模型中将它们声明为可为null的int:
// 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; }
public int? somenullableintfield { get; set; }
另一个选择是告诉EF允许该列为空:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<SomeObject>().Property(m => m.somefield).IsOptional();
base.OnModelCreating(modelBuilder);
}
此代码应位于继承自的对象中DbContext
。
在Ef .net核心中,您可以执行两个选择:首先带有数据注释:
public class Blog
{
public int BlogId { get; set; }
[Required]
public string Url { get; set; }
}
或使用流利的api:
class MyContext : DbContext
{
public DbSet<Blog> Blogs { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Blog>()
.Property(b => b.Url)
.IsRequired(false)//optinal case
.IsRequired()//required case
;
}
}
public class Blog
{
public int BlogId { get; set; }
public string Url { get; set; }
}
还有更多的细节在这里