表达式树和显示

时间:2014-02-04 01:14:52

标签: c# asp.net-mvc-4

我正在尝试让表达式树与我的数据设置一起工作。

以下是数据和我返回到我的视图的内容,例如return View(contacts1)

var contacts1 = (from con in db.Contacts
join conorg in db.ContactOrganizations on con.ContactID equals conorg.ContactID
join org in db.Organizations on conorg.OrganizationID equals org.OrganizationID
where con.CenterID == cID && conorg.IsActive == 1 && con.IsDeleted == 0
orderby con.LastName

select new ContactView
{
        ContactID = con.ContactID,
        FName = con.FirstName,
        LName = con.LastName,
        Title = con.Title,
        Organization = (org == null ? "(none)" : org.Name),
        City = con.City,
        State = con.State,
        DateCreated = con.DateCreated,
        Notes = con.Notes,
        Status = (con.Status == 1 ? "Active" : "Inactive")
}).ToList();

我的表达式树的代码如下,但它给出了一个错误,即“ContactID”属性为null(System.ArgumentNullException: Value cannot be null. Parameter name: property)。我要创建的查询是queryableData.Where(c => c.ContactID == 38 || c.ContactID == 39)。然后我想将结果与上面的联系人视图集成以显示在视图上。

IQueryable<ContactView> queryableData = contacts1.AsQueryable<ContactView>();

ParameterExpression pe = Expression.Parameter(typeof(string), "c");

Expression left = Expression.Property(pe, typeof(string).GetProperty("ContactID"));
Expression right = Expression.Constant(38, typeof(int));
Expression e1 = Expression.Equal(left, right);

left = Expression.Property(pe, typeof(string).GetProperty("ContactID"));
right = Expression.Constant(39, typeof(int));
Expression e2 = Expression.GreaterThan(left, right);

Expression predicateBody = Expression.OrElse(e1, e2);

MethodCallExpression whereCallExpression = Expression.Call(
    typeof(Queryable),
    "Where",
    new Type[] { queryableData.ElementType },
    queryableData.Expression,
    Expression.Lambda<Func<string, bool>>(predicateBody, new ParameterExpression[] { pe }));

IQueryable<string> results = queryableData.Provider.CreateQuery<string>(whereCallExpression);

1 个答案:

答案 0 :(得分:1)

这是来自内存,但我认为你错误地使用了Expression.PropertyExpression.Parameter。试试这个:

ParameterExpression pe = Expression.Parameter(typeof(Contact), "c");
// ...
Expression left = Expression.Property(pe, typeof(Contact).GetProperty("ContactID"));
Expression right = Expression.Constant(38, typeof(int));
Expression e1 = Expression.Equal(left, right);
// And so on...