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过程中碰到了问题,整不明白。
代码如下:
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(); }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 == "北京")) -- ?? 什么情况