开发者

Unable to cast object of type 'System.Linq.Expressions.FieldExpression'

开发者 https://www.devze.com 2023-03-29 02:08 出处:网络
I am using LinqKit.dll to do Linq To Entity in my application, as follow : qry = _articleRepo.GetItemsByCulture(Thread.CurrentThread.CurrentCulture.Name)

I am using LinqKit.dll to do Linq To Entity in my application, as follow :

qry = _articleRepo.GetItemsByCulture(Thread.CurrentThread.CurrentCulture.Name)
                                .AsExpandable().Where(x => x.Approved && isInCategory(x.CategoryID, category.CategoryID));

 Func<string, int, bool> isInCategory = (x, y) =>
            {
                IQueryable<string> list = x.Split(',').AsQueryable();

                //Except 
                //x.Except(_);

                return list.Any(z => z == y.ToString());
            };
开发者_如何学JAVA

it gives me error :

System.InvalidCastException: Unable to cast object of type 'System.Linq.Expressions.FieldExpression' to type 'System.Linq.Expressions.LambdaExpression'.

but removing isInCategory(x.CategoryID, category.CategoryID) causes the application to run without problem.

Would please help me ?


Ok, after looking at the code in comments, I can suggest following: Replace string CategoryID on Article to public virtual ICollection<Category> Categories { get; set; }, so EF will create a foreign key. Then, in order to get articles, that are in particular category, you can use code similar to the following:

var articlesInCategory = context.Articles
            .Where(x => x.Language == Thread.CurrentThread.CurrentCulture.Name)
            .Where(x => x.Approved && x.Categories.Any(c => c.CategoryID == c1.CategoryID)).ToList();

And when you want to create new articles, you should use something like:

var c1 = context.Categories.OrderBy(c => c.Title).First();
var c2 = context.Categories.OrderBy(c => c.Title).Skip(1).First();
context.Articles.Add(new Article { Categories = new Collection<Category> { c1, c2 } });
context.SaveChanges();
0

精彩评论

暂无评论...
验证码 换一张
取 消