如何使用Linq和存储库模式导航导航属性?

时间:2014-06-04 19:58:40

标签: c# sql linq entity-framework

使用Geneic Unit of Work and Repository Framework,我尝试使用Linq导航到实体的导航属性。

在我的控制器中,我使用的是存储库模式和工作单元。在此控制器中,_repositoryWebsites

给出以下三个表:

enter image description here

我正在尝试获取Website实体,以及针对特定ContentTypes.DescriptionSourceUrls的所有WebsiteID的{​​{1}}的明确列表。

我可以获得数据的初始部分:

UserId

我有过几次混乱的尝试,包括这样的事情:

var website = _repository
    .Query()
    .Select()
    .Single(u => u.UserId == userId && u.WebsiteGuid == websiteGuid);

该框架使我能够通过 var website = _repository .Query() .Select() .Single(u => u.UserId == userId && u.WebsiteGuid == websiteGuid) .SourceUrls.Any(s => s.ContentTypeId == s.ContentType.ContentTypeId) .Select(new ContentType()); 写出SQL查询,但是我试图避免这种情况。

我可以创建一个新的DTO并将其投射到此。

有关如何使此Linq查询生效的建议?

感谢。

- 更新 -

通过.SelectQuery(...)实体尝试此操作似乎很困难,因为没有直接导航属性Website - Websites

所以,从ContentTypes开始,我尝试了以下内容:

SourceUrls

但是我收到了这个新错误:

  

“包含路径表达式必须引用导航属性   在类型上定义。使用虚线路径进行参考导航   属性和集合导航的Select运算符   属性“。

我也试过通过 var rep2 = _unitOfWork.Repository<SourceUrl>() .Query(q => q.UserId == userId) .Include(i => i.ContentType.Description.Distinct()) .Include(i => i.Website) .Select().Where(w => w.Website.WebsiteGuid == websiteGuid).ToList(); 进行链接但不完全在那里......

1 个答案:

答案 0 :(得分:0)

我没有您的数据模型可供使用,但似乎在我的本地系统上运行:

using System.Linq;
using System.Data.Entity;

public class Class1
{
    public Class1()
    {
        var website = _repository
            .Where(w => w.UserId == userIdArg && w.WebsiteGuidArg == websiteGuidArg)
            .
    }
}

您的模型可能会为您Distinct()带来不同程度的成功,但重要的是您可以使用include来确保加载集合。

我已经制作了这个答案社区维基,以防任何新发现需要对其进行更改。