Nullable property to entity field, Entity Framework through Code First

后端 未结 4 1615
一整个雨季
一整个雨季 2020-12-05 03:32

Using the data annotation Required like so:

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

Will set somefield to Not

相关标签:
4条回答
  • 2020-12-05 04:09

    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.

    0 讨论(0)
  • 2020-12-05 04:10

    In Ef .net core there are two options that you can do; first with data annotations:

    public class Blog
    {
        public int BlogId { get; set; }
        [Required]
        public string Url { get; set; }
    }
    

    Or with fluent 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; }
    }
    

    There are more details here

    0 讨论(0)
  • 2020-12-05 04:11

    Just omit the [Required] attribute from the string somefield property. This will make it create a NULLable column in the db.

    To make int types allow NULLs in the database, they must be declared as nullable ints in the model:

    // 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; }
    
    0 讨论(0)
  • 2020-12-05 04:22

    Jon's answer didn't work for me as I got a compiler error CS0453 C# The type must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method

    This worked for me though:

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<SomeObject>().HasOptional(m => m.somefield);
        base.OnModelCreating(modelBuilder);
    }
    
    0 讨论(0)
提交回复
热议问题