c# - linq to sql 查询帮助

标签 c# linq linq-to-sql c#-4.0

基于下表

Sample
Id     Name
---------------
S1     SomeName
S2     OtherName
S3     AnotherName

AlreadyUsed
Id
---------
S2

Reference
Id    FkId
---------
T1    S1
T2    S1

我想要实现以下目标 “仅从示例表中选择那些在 AlreadyUsed 中没有条目且在 引用表。”

我能够为第一部分编写查询,但对后半部分感到困惑。下面是我可以想出的“仅从示例表中选择那些在 AlreadyUsed 表中没有条目的条目”

var count = 50;

var alreayUsed = from au in repository.GetEntity<AlreadyUsed>() 
                 select au.Id;

var notUsed = (from nu in repository.GetEntity<Sample>()
              where !alreadyUsed.Contains(nu.Id)
              orderby nu.Name
              select new CustomClass
              {
                 CName = nu.Name,
                 CId = nu.Id
              }).Take(count).ToArray();

另外,请。建议是否有更好的方法来编写上述查询。

谢谢。

最佳答案

var count = 50;

var alreayUsed = from au in repository.GetEntity<AlreadyUsed>() 
                 select au.Id;

var notUsed = (from nu in repository.GetEntity<Sample>()
              where !alreadyUsed.Contains(nu.Id) && nu.References.Count() > 0
              orderby nu.Name
              select new CustomClass
              {
                 CName = nu.Name,
                 CId = nu.Id
              }).Take(count).ToArray();

请注意,我添加了“nu.References.Count() > 0”

我假设您在数据模型中正确设置了名为“References”的关联关系,以便每个 Sample 对象都有许多“Reference”对象。

关于c# - linq to sql 查询帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5072509/

相关文章:

c# - 调用不带括号的函数?

c# - ASP.NET Core HTTPRequestMessage 返回奇怪的 JSON 消息

c# - LINQ 获取 TreeView 中最深层次的节点

C#加入群组查询

c# - 如何使用通用的 getter 和 setter 设置只读属性的值?

entity-framework - 导航属性上的 EF Core 组

c# - 无法在 C# 中隐式转换类型 'System.Collections.Generic.List<AnonymousType#1>

.net - ASP.NET MVC 中的 LINQ to SQL 导致 DuplicateKeyException

c# - 在 LINQ 中选择大小写

C# 在 AD 中链接组策略