Search code examples
c#lambdaexpression-trees

Property is not defined for type when i want to build expression


I Want to build an expression to query into my database by EF Core 2.1

I have my Data class that represent entity from my table:

public class Data
{
    public string Id1 {get;set;}
    public string Id2 {get;set;}
}

Then i want to build some expression:

var parameter = Expression.Parameter(typeof(Data), "x");
var memberId1 = Expression.Field(parameter, nameof(Data.Id1));
var memberId2 = Expression.Field(parameter, nameof(Data.Id2));

When i want to make Field from Id1, i get this expcetion:

System.ArgumentException: Instance field 'Id1' is not defined for type 'Entities.Data' at System.Linq.Expressions.Expression.Field(Expression expression, String fieldName)

How to get acces intoo field from my Data class?


Solution

  • My Id1 and Id2 is not Field but Property. Now it works:

    var parameter = Expression.Parameter(typeof(Data), "x");
    var memberId1 = Expression.Property(parameter, nameof(Data.Id1));
    var memberId2 = Expression.Property(parameter, nameof(Data.Id2));