Code First Entity Framework和Lambda表达式First/Where可能会组成的陷阱

来源:互联网 发布:涂涂乐 源码购买 编辑:程序博客网 时间:2024/06/06 15:50

环境:.NET Framework 4.0, Code First ENtity Framework 4.x

Lambda表达式First和Where在取一条数据时可以互换。但是当关联多表并使用First时就会出现错误,下面是错误之一:

Unable to create a constant value of type 'ICStars2_0.Model.Article2Category'. Only primitive types or enumeration types are supported in this context.

报错代码:

using (var db = new DbContext())
            {
                return
                    db.Categories.First(c => db.Article2Categories.Any(
                        a2c =>
                            a2c.CategoryID == c.ID &&
                            db.Articles.Any(a => a.UrlTitle.Equals(urlTitle) && a.ID == a2c.ArticleID)));
            }

解决方案:

using (var db = new DbContext())
            {
                return
                    db.Categories.Where(
                        c =>
                            db.Article2Categories.Any(
                                a2c =>
                                    a2c.CategoryID == c.ID &&
                                    db.Articles.Any(a => a.UrlTitle.Equals(urlTitle) && a.ID == a2c.ArticleID))).First();
            }

对应SQL语句:

select * from category where exists(

    select * from article2category where category.ID=CategoryID and exists(

        select * from article where ID=article2category.ArticleID and UrlTitle='urlTitle'

    )

)

当使用Resharper重构时,就会把正确的WHERE子句改成FIRST子句,进而报错。 有时需要慎用Resharper, 它会重构出冗余代码又可能会重构出错误。