带有连接的LINQ和一个List <guid> </guid>

时间:2010-11-23 13:39:56

标签: .net linq entity-framework join linq-to-entities

这是我用来构建LINQ语句原型的SQL。代码中的GUID是List<GUID>。我尝试了3个小时,但是没有得到它。可以在睡梦中写一些LINQ的人可以帮助我。

SELECT DISTINCT  [id]
      ,[emailAddress]
      ,[name]
      ,[emailRunNumber]
  FROM [emailAddress]
  join promotionsJoin
  on promotionsJoin.EmailAddressId = emailAddress.id
  where promotionsJoin.promotionId in ('09464b57-f3d7-41ec-b0b1-cbc5999824bd',
  '8bc855b2-2f01-4083-b43a-dab7b7a81ac8') AND emailRunNumber is NULL

3 个答案:

答案 0 :(得分:1)

(from emailAddress in emailAddresses
 join promotion in promotions 
   on emailAddress.id equals promotion.EmailAddressId
 where guidsList.Contains(promotion.promotionId)
    && promotion.emailRunNumber == null
 select new {
     emailAddress.id,
     emailAddress.emailAddress,
     promotion.name,
     promotion.emailRunNumber
}).Distinct()

如果映射中的两个表之间已经存在关联,那么此处的连接将是不必要的(那么promotion将只是emailAddress之外的字段)

答案 1 :(得分:0)

linq-to-entities不支持in运算符,但您可以这样做。

var result = YourObjectContext.EmailAddress
                .Where(ea => ea.emailRunNumber == null 
                && (ea.PromotionJoin.promotionId == new Guid("09464b57-f3d7-41ec-b0b1-cbc5999824bd") || 
                    ea.PromotionJoin.promotionId == new Guid("8bc855b2-2f01-4083-b43a-dab7b7a81ac8"));

EF生成的名为EmailAddress的类将自动拥有一个名为PromotionJoin的字段,前提是您的PromotionJoin表具有对EmailAddress主键的外键引用。< / p>

答案 2 :(得分:0)

扩展@Klaus的回答:

var result = YourObjectContext.EmailAddress
    .Where(ea =>
        ea.emailRunNumber == null &&
        new[]
        {
            new Guid("09464b57-f3d7-41ec-b0b1-cbc5999824bd"),
            new Guid("8bc855b2-2f01-4083-b43a-dab7b7a81ac8"
        }.Contains(ea.PromotionJoin.promotionId))
    .Distinct();

var result = YourObjectContext.EmailAddress
    .Where(ea =>
        ea.emailRunNumber == null &&
        new[]
        {
            "09464b57-f3d7-41ec-b0b1-cbc5999824bd",
            "8bc855b2-2f01-4083-b43a-dab7b7a81ac8"
        }.Select(s => new Guid(s)).Contains(ea.PromotionJoin.promotionId));
    .Distinct();