可空属性为实体领域,通过代码第一次实体框架(Nullable property to entity

2019-06-24 17:14发布

使用数据注解Required像这样:

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

将somefield设置为Not Null数据库,如何设置somefield为允许空值?我试图通过SQL Server Management Studio中设置,但实体框架设置回Not Null

Answer 1:

只是省略从该[必需]属性string somefield财产。 这将使创建一个NULL的数据库能够列。

为了使INT类型允许在数据库中的NULL,他们必须声明为模型可空整数:

// 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; }


Answer 2:

另一种选择是告诉EF允许柱为空:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
        modelBuilder.Entity<SomeObject>().Property(m => m.somefield).IsOptional();            
        base.OnModelCreating(modelBuilder);
}

此代码应该是在继承的对象DbContext



Answer 3:

乔恩的回答并没有为我工作,我得到了一个编译器错误CS0453 C#的类型必须是为了在泛型类型或方法来使用它作为参数“T”非空值类型

这为我工作,但:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<SomeObject>().HasOptional(m => m.somefield);
    base.OnModelCreating(modelBuilder);
}


Answer 4:

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; }
}

还有更多的细节在这里



文章来源: Nullable property to entity field, Entity Framework through Code First