Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Required property but Nullable, Entity Framework through Code First

How to make a property required (for field validation) but Nullable for the DB code migrations?

I do have a DB table with a thousand entries. recently was required to add a required DateTime property.

    [Required]
    [Display(Name = "Birth", Order = 10)]
    public DateTime? Birth { get; set; } 

If I set [Required] annotation, the Code first migration will add NOT NULL to the column declaration. However all current entries does not have "Birth" data. and it will be NULL.

the Birth property should be required to the view field validatoin, but it could be nullable into the DB. Is that possible somehow?

I already tried add "?" (nullable) to the property and "virtual" without success.

like image 860
Daniel Santos Avatar asked Aug 06 '16 02:08

Daniel Santos


2 Answers

Use your model for DB/Entity communication.

Use a View Model for your UI layer. Mark Required on the property in the ViewModel, mark Nullable on the model. Perform casting in your code as needed. Move all the UI-related attribute decoration (like Display, validation/etc) to the ViewModel as well.

Casting can automatically be performed with the AutoMapper plugin, available via the NuGet package manager.

like image 103
mariocatch Avatar answered Nov 09 '22 06:11

mariocatch


One quick way could be overriding the OnModelCreating() method of your DB Context.

This way :

public class AppContext : DbContext
{
   protected override void OnModelCreating(DbModelBuilder modelBuilder)
   {
      // ...
      modelBuilder.Entity<YourModelEntity>.Property(p => p.Birth).IsOptional();
   }

}

or another proper way is that you can create an extended class of the generic EntityTypeConfiguration type for your model and then add this specific configuration to the DBModelBuilder in the OnModelCreating() method this way :

public class YourModelTypeConfiguration : EntityTypeConfiguration<YourModelType>
{
    public YourModelTypeConfiguration()
    {
        // ... some other configurations ;

        Property(p => p.Birth).IsOptional();
    }
}

Note that you need the

using System.Data.Entity.ModelConfiguration; 

at top of your class file.

Then in the OnModelCreating() method you should add this :

    public class AppContext : DbContext
{
   protected override void OnModelCreating(DbModelBuilder modelBuilder)
   {
      // quick and dirty solution
      // modelBuilder.Entity<YourModelEntity>.Property(p => p.Birth).IsOptional()

      // cleaner solution
      modelBuilder.Configurations.Add(new YourModelTypeConfiguration());
   }

}

This way you keep your specific configurations separated and don't mix everything together.

When applying code first migration the "Birth" database field should be nullable.

I hope this helps.

like image 39
TaiT's Avatar answered Nov 09 '22 07:11

TaiT's