1

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 Answer 1

3

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");
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.