0

I am trying to stay consistent within my demo app using the AdventureWorks2012 database and EF, but I need some help translating this Linq statement into extension methods.

return (from person in this.context.Persons
        from email in this.context.EmailAddresses
        where email.EmailAddress == emailAddress
        select person).FirstOrDefault();

The objects are:

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; }
}

Where the BusinessEntityId is the PK. Any help is greatly appreciated. Thanks...

1 Answer 1

3

Below I'll answer your question exactly. However, I don't really see why you would want to have your query translated to extension methods, so I think this answer is not the answer you're looking for. If so, could you dive into the terminology and rephrase the question?


First: LINQ query syntax is just nice syntactic sugar for extension methods. Your code:

return (from person in this.context.Persons
        from email in this.context.EmailAddresses
        where email.EmailAddress == emailAddress
        select person).FirstOrDefault();

Below is the LINQ query syntax translated to extension methods. The two are equivalent, they do exactly the same and give the same result:

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();

It is just not as nice to read, and it is harder to understand.

Sign up to request clarification or add additional context in comments.

1 Comment

It is just not as nice to read, and it is harder to understand. I believe the opposite.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.