Nullable property to entity field, Entity Framework through Code First

后端 未结 4 1627
一整个雨季
一整个雨季 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: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 Blogs { get; set; }
    
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity()
                .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

提交回复
热议问题