Mapping Non-Public Members With Entity Framework Code First
This is a common request, and really makes sense; we need to use LINQ expressions and a bit of reflection magic. First, an helper function for returning an expression that points to a member:
1: public static class ExpressionHelper
2: {
3: public static Expression<Func<TEntity, TResult>> GetMember<TEntity, TResult>(String memberName)
4: {
5: ParameterExpression parameter = Expression.Parameter(typeof(TEntity), "p");
6: MemberExpression member = Expression.MakeMemberAccess(parameter, typeof(TEntity).GetMember(memberName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance).Single());
7: Expression<Func<TEntity, TResult>> expression = Expression.Lambda<Func<TEntity, TResult>>(member, parameter);
8: return (expression);
9: }
10: }
Then, we call it on the DbContext.OnModelCreating method, as a parameter to StructuralTypeConfiguration<TStructuralType>.Property:
1: protected override void OnModelCreating(DbModelBuilder modelBuilder)
2: {
3: modelBuilder.Entity<Project>().Property(ExpressionHelper.GetMember<Project, Decimal>("Budget")).IsRequired();
4:
5: base.OnModelCreating(modelBuilder);
6: }