我有两个表(客户端和电子邮件),一个包含客户的数据,包括一个主电子邮件地址,另一个包含其他电子邮件地址。
我需要从众多电子邮件地址中的一个验证用户,无论是在客户端还是电子邮件表中。我想出了这个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中编写此查询?
答案 0 :(得分:1)
如果我理解正确,
客户可能会或可能不会在emails
表格中收到电子邮件(附加)。
此外,客户在emails
表中还有多个附加电子邮件条目。如下所示
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" },
};
在这种情况下,请使用以下查询完成此操作,
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
};
我希望它可以帮到你。