I'm using code first with fluent API in Entity Framework Core to determinate behaviors for properties.
I wondering if there is any way to replace this part.
modelBuilder.Entity<Person>()
.Property(b => b.Name)
.IsRequired();
modelBuilder.Entity<Person>()
.Property(b => b.LastName)
.IsRequired();
modelBuilder.Entity<Person>()
.Property(b => b.Age)
.IsRequired();
With a something like this:
modelBuilder.Entity<Person>()
.AllProperties()
.IsRequired();
The point is that sometimes most properties or even all need to be NOT NULL. And it's not elegant to mark each property.
A solution may be using reflection:
var properties = typeof(Class).GetProperties();
foreach (var prop in properties)
{
modelBuilder
.Entity<Class>()
.Property(prop.PropertyType, prop.Name)
.IsRequired();
}
Note that ALL of the properties will be setted as required. Of course you may filter the properties to be setted as required based on type (for example).
UPDATE
Using an extension method you can make it much cleaner.
EntityTypeBuilderExtensions.cs
public static class EntityTypeBuilderExtensions
{
public static List<PropertyBuilder> AllProperties<T>(this EntityTypeBuilder<T> builder,
Func<PropertyInfo, bool> filter = null) where T : class
{
var properties = typeof(T)
.GetProperties()
.AsEnumerable();
if (filter != null)
{
properties = properties
.Where(filter);
}
return properties
.Select(x => builder.Property(x.PropertyType, x.Name))
.ToList();
}
}
Usage in your DbContext
:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder
.Entity<Class>()
.AllProperties()
.ForEach(x => x.IsRequired());
}
If you want to apply IsRequired
only to particular properties of a class you can pass a filter function to the AllProperties
method.
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
//Required is applied only for string properties
modelBuilder
.Entity<Class>()
.AllProperties(x => x.PropertyType == typeof(string))
.ForEach(x => x.IsRequired());
}