繁体   English   中英

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

[英]How to navigate navigation properties using Linq and a repository pattern?

使用通用工作单元和存储库框架 ,我尝试使用Linq导航到实体的导航属性。

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

给出以下三个表:

在此处输入图片说明

我正在尝试获取Website实体,以及针对特定WebsiteIDUserId所有SourceUrlsContentTypes.Description的不同列表。

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

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());

该框架使我能够通过.SelectQuery(...)编写SQL查询,但是我正尝试避免这种情况。

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

有关如何使此Linq查询正常工作的建议?

谢谢。

-更新-

由于没有直接导航属性“ Websites ContentTypes ,因此尝试通过“ Website实体进行尝试似乎很困难。

因此,从SourceUrls开始,我尝试了以下操作:

                    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();

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

“包含路径表达式必须引用在类型上定义的导航属性。对于引用导航属性,请使用虚线路径,对于集合导航属性,请使用Select运算符。”

我也尝试通过.Select()进行链接,但还不完全如此...

我没有要使用的数据模型,但是这似乎在我的本地系统上起作用:

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来确保加载了集合。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM