Ozan Yurtsever
Ozan Yurtsever

Reputation: 1304

Ignore a property with PropertyInfo

I want to ignore a property with a property info such that;

PropertyInfo propertyInfo = typeof(GLAccount).GetProperty("ExampleProp");
modelBuilder.Entity<GLAccount>().Ignore(g => propertyInfo);

The above code block gives me the following error;

The expression 'g => value(Dashboard.DAL.Context+<>c__DisplayClass16_0).propertyInfo' is not a valid property expression. The expression should represent a property: C#: 't => t.MyProperty'  VB.Net: 'Function(t) t.MyProperty'.'

How can I solve this? Thanks.

Upvotes: 2

Views: 107

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1064324

If you're using an API that expects an exppression-tree, you will need to build the lambda manually:

var p = Expression.Parameter(typeof(GLAccount));
var body = Expression.Property(p, propertyInfo);
var lambda = Expression.Lambda<Func<GLAccount, SomeType>>(body, p);
modelBuilder.Entity<GLAccount>().Ignore(lambda);

The problem here, though, is going to be knowing the SomeType. I'm assuming that Ignore(...) is actually Ignore<TResult>(...) or similar, in which the TResult would need to be the same as the SomeType above, which would need to be whatever the return type of ExampleProp is. You may need to use MakeGenericMethod here.

Also note that if you aren't doing anything else with propertyInfo, you can also use Expression.Property(p, "ExampleProp") as a short-cut.

Although... from these docs, you might be able to simply use:

modelBuilder.Entity<GLAccount>().Ignore("ExampleProp");

Upvotes: 2

Related Questions