Invalid property for object field, Entity Framework via First code

Using Required data annotation as follows:

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

Somefield will be set to Not Null in the database, how can I install somefield to allow NULL ?, I tried to install it through SQL Server Management Studio, but the Entity Framework returned it to Not Null .

+58
nullable asp.net-mvc-3 entity-framework code-first
May 22 '12 at 9:23
source share
4 answers

Just omit the [Required] attribute from the string somefield . This will create a NULL able column in db.

To make int types nullable in the database, they must be declared as null 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; } 
+89
May 22 '12 at 22:13
source share

Another option is to specify EF so that the column is null:

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

This code must be in an object that inherits from DbContext .

+28
Aug 01 2018-12-12T00:
source share

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

This worked for me:

 protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity<SomeObject>().HasOptional(m => m.somefield); base.OnModelCreating(modelBuilder); } 
+3
Jul 14 '16 at 17:16
source share

There are two options in Ef.net core that you can do; First with data annotations:

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

Or with a quick API:

 class MyContext : DbContext { public DbSet<Blog> Blogs { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Blog>() .Property(b => b.Url) .IsRequired(); } } public class Blog { public int BlogId { get; set; } public string Url { get; set; } } 

There is more detailed information here.

0
Dec 18 '18 at 10:44
source share



All Articles