Entity Framework : data fetching from child table join parent table

Last Reply 10 months ago By Shashikant

Posted 10 months ago

Hi ,

 Here My tables are  

Transactions (child) , Users(Parent)

Transactions Data :

Id    amt     Userid
1     200      1
2    100      2
3    10        1

Users Data :

 

ID      type

1     admin
2      customer

Now using linq query i want to fetch all the custoemr transactions. Please let me know the solution

Posted 10 months ago

Hi,

Please refer below code.

C#

List<Users> users = new List<Users>();
users.Add(new Users
{
    Id = 1,
    Type = "admin"
});
users.Add(new Users
{
    Id = 2,
    Type = "customer"
});

List<Transactions> transactions = new List<Transactions>();
transactions.Add(new Transactions
{
    Id = 1,
    UserId = 1,
    Amount = 200
});
transactions.Add(new Transactions
{
    Id = 2,
    UserId = 2,
    Amount = 200
});
transactions.Add(new Transactions
{
    Id = 3,
    UserId = 1,
    Amount = 200
});


List<Transactions> customerTransactions = (from transaction in transactions
                                            join user in users on transaction.UserId equals user.Id
                                            where user.Id == 1
                                            select transaction).ToList<Transactions>();

Transactions and Users Class

public class Transactions
{
    public int Id { get; set; }
    public int UserId { get; set; }
    public int Amount { get; set; }
}

public class Users
{
    public int Id { get; set; }
    public string Type { get; set; }
}

I hope this will help you out.

I agree, here is the link: http://e-iceblue.com/free-api