我正在尝试使用AdventureWorks2012数据库和EF在我的演示应用程序中保持一致,但我需要一些帮助将此Linq语句转换为扩展方法。
return (from person in this.context.Persons
from email in this.context.EmailAddresses
where email.EmailAddress == emailAddress
select person).FirstOrDefault();
对象是:
public class Person
{
public int BusinessEntityId { get; set; }
public string PersonType {get;set;}
public bool NameStyle { get; set; }
public string Title { get; set; }
public string FirstName { get; set; }
public string MiddleName { get; set; }
public string LastName { get; set; }
public string Suffix { get; set; }
public int EmailPromotion { get; set; }
public PersonPassword Password { get; set; }
public virtual ICollection<PersonEmailAddress> EmailAddresses { get; set; }
}
public class PersonEmailAddress
{
public int BusinessEntityId { get; set; }
public int EmailAddressId { get; set; }
public string EmailAddress { get; set; }
public virtual Person Person { get; set; }
}
public class PersonPassword
{
public int BusinessEntityId { get; set; }
public string PasswordHash { get; set; }
public string PasswordSalt { get; set; }
public virtual Person Person { get; set; }
}
BusinessEntityId是PK的位置。 任何帮助是极大的赞赏。感谢...
答案 0 :(得分:3)
下面我将完全回答你的问题。但是,我真的不明白为什么你想将你的查询翻译成扩展方法,所以我认为这个答案不是你想要的答案。如果是这样,你可以深入研究术语并重新解释这个问题吗?
首先:LINQ查询语法对于扩展方法来说是很好的语法糖。你的代码:
return (from person in this.context.Persons
from email in this.context.EmailAddresses
where email.EmailAddress == emailAddress
select person).FirstOrDefault();
以下是转换为扩展方法的LINQ查询语法。两者是等价的,它们完全相同并给出相同的结果:
return this.context.Persons
.SelectMany(p => this.context.EmailAddresses,
(p, e) => new { Person = p, Email = e})
.Where(pe => pe.Email == pe.Person)
.Select(pe => pe.Person)
.FirstOrDefault();
阅读起来不太好,而且更难理解。