1
votes

So I'm using the 'CodeFirst' methodology of Entity Framework and I have mapping files to map the table information and add in things such as validation so for instance:

this.Property(t => t.AccountName)
            .IsRequired()
            .HasMaxLength(25);

This is using the Fluent API and I'm wondering how to get the property name by string instead of t.AccountName. I'm wanting to dynamically set these properties and I just don't know how to do that programmatically.

1

1 Answers

3
votes

Without commenting on whether this is advisable or not(!), you can achieve what you need because the Property() method takes an expression tree as its parameter. Consider the following:

public class MyEntity
{
    [Key]
    public int MyEntityId { get; set; }

    public string MyProperty { get; set; }
}

public class MyContext : DbContext
{
    public DbSet<MyEntity> MyEntities
    {
        get { return this.Set<MyEntity>(); }
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        var param = Expression.Parameter(typeof(MyEntity));

        var propertyExpression = Expression.Lambda(Expression.Property(param, "MyProperty"), param);

        modelBuilder.Entity<MyEntity>()
            .Property((Expression<Func<MyEntity, string>>)propertyExpression)
            .HasColumnName("Fish");
    }
}

Here I build configuration for the MyProperty column, which I refer to by name in a lambda expression.

The above code works for string properties, but would require some modification to work for any property type. The cast to Expression<Func<MyEntity, string>> hard-codes the property type, but we can eliminate the cast using the dynamic language feature.

        var param = Expression.Parameter(typeof(MyEntity));
        dynamic propertyExpression = Expression.Lambda(Expression.Property(param, "MyProperty"), param);

        modelBuilder.Entity<MyEntity>()
            .Property(propertyExpression)
            .HasColumnName("FishFace");