日期:2014-05-20  浏览次数:20984 次

EF中使用Expression拼接复合查询的问题!
大家好,请教Expression拼接查询条件的问题!

参考了http://www.cnblogs.com/lyj/archive/2008/03/25/1122157.html
和http://www.cnblogs.com/killuakun/archive/2008/08/03/1259389.html
大概了解了怎么利用Expression拼接条件,但在实际写demo过程中碰到了问题,整不明白。

代码如下:
C# code

        static void Main(string[] args)
        {
            OscarEntities db = new OscarEntities(); //数据模型 DbContext
            IQueryable first = db.Citys;
            ParameterExpression param = Expression.Parameter(typeof(City), "c");
            Expression right = Expression.Constant("北京");
            Expression left = Expression.Property(param, typeof(City).GetProperty("Name"));
            Expression filter = Expression.Equal(left, right); // Name='北京'
            Expression pred = Expression.Lambda(filter, param);
            MethodCallExpression call = Expression.Call(typeof(Queryable), "Where", new Type[] { typeof(City) },
                Expression.Constant(first), pred);
            var result = db.Citys.AsQueryable().Provider.CreateQuery<City>(call);
            Console.WriteLine(result.ToString()); //报错:无法创建City类型常量,此上下文仅支持基元类型
            Console.Read();
        }



我跟踪了一下call,发现call.ToString()居然是这样的:

SQL code

SELECT 
[Extent1].[Id] AS [Id], 
[Extent1].[ProvinceId] AS [ProvinceId], 
[Extent1].[Name] AS [Name], 
[Extent1].[AreaCode] AS [AreaCode], 
[Extent1].[PhoneCode] AS [PhoneCode]
FROM [dbo].[Citys] AS [Extent1].Where(c => (c.Name == "北京"))  -- ?? 什么情况



我感觉是拼接方法错了,不知道正确的应该怎么写?




------解决方案--------------------
var result = db.Citys.AsQueryable().Provider.CreateQuery<City>(call);
Console.WriteLine(result.ToString()); 

此处result是一个结果集,怎么能直接输出result.ToString()?

你需要这样来输出:

foreach(var r in result)
Console.WriteLine(r.Name);

其他的没看出什么问题
------解决方案--------------------
static void Main(string[] args)
{
JxzxCarEntities db = new JxzxCarEntities();

Expression<Func<BrandType, bool>> filter =
(m => m.FirstWord == "a"
&&
m.Name.Contains("阿"));

var list = db.BrandType.Where(filter).ToList();

foreach (var item in list)
{
Console.WriteLine("{0} {1}", item.Name, item.FirstWord);
}

Console.Read();
}