2 回答

TA贡献1804条经验 获得超2个赞
好吧,您可以像在 SQL 中一样完成它,但使用导航属性而不是连接。
我将使用 LINQ 查询语法,因为它能更好地显示相似性,而且方法语法对于此类查询来说非常复杂且难以阅读:
from a in _context.Article
from ab in a.ReferenceArticleFromNavigations
let b = ab.ArticleToNavigation
from bc in b.ReferenceArticleFromNavigations
let c = bc.ArticleToNavigation
where a.ArticleNo = "1234"
select new Reference
{
ArticleFromNavigation = a,
ArticleToNavigation = c,
}
这些let语句不是很需要(您可以直接使用引用导航属性),我包含它们只是为了使 LINQ 查询更接近 SQL 查询。
实际上,在这种情况下等效方法并没有那么糟糕 - 使用嵌套将多个级别展平SelectMany并使用重载投影 (top, bottom) 对,SelectMany允许:
_context.Article
.Where(a => a.ArticleNo = "1234")
.SelectMany(a => a.ReferenceArticleFromNavigations
.SelectMany(ab => ab.ArticleToNavigation.ReferenceArticleFromNavigations)
// include as many `SelectMany` like the above as you wish until you hit the desired level of nesting
.Select(bc => bc.ArticleToNavigation),
(a, c) => new Reference
{
ArticleFromNavigation = a,
ArticleToNavigation = c,
});

TA贡献1808条经验 获得超4个赞
我将数据库建模为类以使语法正确。请参阅下面的代码:
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication107
{
class Program
{
static void Main(string[] args)
{
Context _context = new Context();
string ArticleNo = "1234";
var results = (from a in _context.article.Where(x => x.Id == ArticleNo)
join ab in _context.reference
.Where(x => (x.ArticleFromId == x.ArticleToId))
on a.Id equals ab.ArticleFromId
select new { a = a, ab = ab }
).Select(r => new Reference()
{
ArticleFromNavigation = r.a,
ArticleToNavigation = r.a.ReferenceArticleToNavigations.ToList()
}).ToList();
}
}
public class Context
{
public List<Reference> reference { get; set; }
public List<Article> article { get; set; }
}
public class Reference
{
public string ArticleFromId { get; set; }
public string ArticleToId { get; set; }
public Article ArticleFromNavigation { get; set; }
public List<string> ArticleToNavigation { get; set; }
}
public class Article
{
public string Id { get; set; }
public List<string> ReferenceArticleToNavigations { get; set; }
}
}
- 2 回答
- 0 关注
- 128 浏览
添加回答
举报