chr*_*mon 65 entity-framework nullable code-first asp.net-mvc-3
Required像这样使用数据注释:
[Required]
public int somefield {get; set;}
Run Code Online (Sandbox Code Playgroud)
将somefield设置为Not Null数据库,如何设置某个字段
以允许NULL?,我尝试通过SQL Server Management Studio设置它,但实体框架将其设置回Not Null.
dan*_*wig 101
只需省略属性中的[Required]属性即可string somefield.这将使它NULL在db中创建一个有能力的列.
要使int类型允许数据库中的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; }
Run Code Online (Sandbox Code Playgroud)
Jon*_*Jon 29
另一个选项是告诉EF允许列为null:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<SomeObject>().Property(m => m.somefield).IsOptional();
base.OnModelCreating(modelBuilder);
}
Run Code Online (Sandbox Code Playgroud)
此代码应该在继承自的对象中DbContext.
nzr*_*tmn 12
在Ef .net core中,您可以执行两个选项;首先是数据注释:
public class Blog
{
public int BlogId { get; set; }
[Required]
public string Url { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
或者使用流畅的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; }
}
Run Code Online (Sandbox Code Playgroud)
还有更多的细节在这里