17CrazyBrain
17CrazyBrain

Reputation: 63

How to fetch data to multiple entity objects using single Linq statement

I have two entity classes

[Table("Payment")]
public class Payment
{
    public Payment()
    {
        this.SchemeMember = new HashSet<SchemeMember>();
    }
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public long PaymentUid { get; set; }

    /// <summary>
    /// Member U id
    /// </summary>
    public int MemberUid { get; set; }


    public  ICollection<SchemeMember> SchemeMember { get; set; }
}

public class SchemeMember
{
    /// <summary>
    /// Gets or sets Member UID
    /// </summary>
    public int MemberUid { get; set; }
}

These two entities are related by MemberUid. Now when I try to fetch the data using the below LINQ, SchemeMember count is always 0. I have already disabled Lazyloading to false.

var result =  (from payment in this.DbContext.Payment
             join schemeMember in this.DbContext.SchemeMember on 
                                   Payment.MemberUid equals 
                                   schemeMember.MemberUid 
             select payment).ToList();

Can any one kindly help me to figure out the issue? Thanks in advance.

Upvotes: 0

Views: 112

Answers (1)

Steve Py
Steve Py

Reputation: 34653

If your mappings are set up correctly, you shouldn't need to do any of that, use the references and let EF do the work.

Assuming you wanted to find payments with schema members that had a Value = "X":

var payments = DbContext.Payment.Where(p=>p.SchemeMember.Any(s=>s.Value == "X")).ToList();

Note: I've used the Fluent Linq methods, never did find the Linq-like-SQL syntax very intuitive. :)

I'd recommend using plural naming convention for child collection classes: I.e. Payment.SchemeMembers as it makes it very easy to visually resolve your single associations (I have a scheme member) from your multi ones. (I have a number of scheme members)

Upvotes: 1

Related Questions