88

像这样使用数据注释Required

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

将在数据库中设置somefieldNot Null,如何设置somefield以 允许 NULL?,我尝试通过 SQL Server Management Studio 设置它,但 Entity Framework 将其设置回Not Null.

4

4 回答 4

129

只需从属性中省略 [Required] 属性即可string somefield。这将使它NULL在数据库中创建一个有能力的列。

要使 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; }
于 2012-05-22T22:13:02.550 回答
34

The other option is to tell EF to allow the column to be null:

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

This code should be in the object that inherits from DbContext.

于 2012-08-01T15:19:18.590 回答
16

Ef .net 核心中,您可以执行两个选项;首先是数据注释:

public class Blog
{
    public int BlogId { get; set; } // optinal case

    [Required]
    public string Url { get; set; } // required case
}

或者使用流利的 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; }
}

这里有更多细节

于 2018-12-18T10:44:42.103 回答
4

Jon 的回答对我不起作用,因为我收到编译器错误CS0453 C# The type must be an non-nullable value type in order to use it as parameter 'T' in the generic type or method

不过,这对我有用:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<SomeObject>().HasOptional(m => m.somefield);
    base.OnModelCreating(modelBuilder);
}
于 2016-07-14T17:16:01.603 回答