Required property, but Nullable, Entity Framework via First code

How to make required property (for field check), but Nullable for DB code migration?

I have a DB table with a thousand records. recently it was required to add the required DateTime property.

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

If I set the annotation [Required], the first code migration will add NOT NULL to the column declaration. However, all current records do not have birth data. and it will be NULL.

The property Birthmust be required for the viewport, but it can be NULL in the database. Is it possible somehow?

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

+4
source share
2 answers

Use your model to communicate with DB / Entity.

Use the view model for the user interface layer. Sign Required for a property in the ViewModel, check Nullable in the model. Cast in your code as needed. Move all attribute attributes associated with the user interface (e.g. Display, validation / etc) and ViewModel.

Casting can be automatically performed using the AutoMapper plugin, available through the NuGet package manager.

+7
source

One quick way could be to override the OnModelCreating () method of your database context.

In this way:

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

}

, EntityTypeConfiguration , DBModelBuilder OnModelCreating() :

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

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

,

using System.Data.Entity.ModelConfiguration; 

.

OnModelCreating() :

    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());
   }

}

, .

"" .

, .

+1

Source: https://habr.com/ru/post/1650379/


All Articles