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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With