1

我有两张表(客户和电子邮件),一张包含客户数据,包括主要电子邮件地址,另一张包含附加电子邮件地址。

我需要从他们的多个电子邮件地址之一验证用户,无论它是在客户端还是电子邮件表上。我想出了这个运行良好的 SQL 语句:

set @email = 'client@domain.com';
select c1.credits > 0 as Allowed, c1.Email as MainEmail from 
customers c1 inner join (select ClientId,  Email FROM customers WHERE 
Email=@email union all select ClientId, Email FROM emails WHERE Email=@email) e1 
on c1.ClientId = e1.ClientId;

如何使用基于方法的语法在 LINQ to Entities 中编写此查询?

4

1 回答 1

1

If i understand correctly,

Customer may or may not have the email (Additional) in emails table. Also, Customer have more than one additional emails entry in emails table. Like below

List<Customer> customers = new List<Customer> 
{ 
    new Customer { ClientId = 1, Email = "client1@domain.com", Credits = 2 },
    new Customer { ClientId = 2, Email = "client2@domain.com", Credits = 1 },
    new Customer { ClientId = 3, Email = "client3@domain.com", Credits = 1 },
};

List<Emails> emails = new List<Emails> 
{ 
    new Emails { ClientId = 1, Email = "client1-2@domain.com" },
    new Emails { ClientId = 1, Email = "client1-3@domain.com" },
    new Emails { ClientId = 2, Email = "client2-1@domain.com" },
};

In that case, Use the below query to get it done,

var result = from c in customers
             let _emails = emails.Where(e => c.ClientId == e.ClientId).Select(t => t.Email)
             where c.Email == "client3@domain.com" || _emails.Contains("client3@domain.com")
             select new
             {
                 Allowed = c.Credits > 0,
                 MainEmail = c.Email
             };

I hope it helps you.

于 2012-11-14T15:57:05.563 回答