可空属性到实体字段,实体框架通过Code First

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)

  • 是的,但它只适用于不是整数类型的字符串. (3认同)
  • 在您的问题中,您的属性是一个字符串.要使int允许空值,必须将其声明为可空的int,如下所示:`public int?somenullableintfield {get; 组; }` (3认同)
  • 那么情况(边缘情况,但我面临的情况),属性用于业务规则验证和mvc的易用性,但需要允许用户保存部分完成的表单(即可能需要一段时间的长表格)做).我需要能够允许EF创建允许空值的列..猜测它在oncreating中使用的模式构建器,但不知道如何 (2认同)

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.

  • 您为什么不使用ViewModels?比在视图模型中可能需要,而在实际模型中则不需要。 (2认同)

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)

还有更多的细节在这里

  • 对于 EF Core,这就是有效的答案。 (2认同)