简体   繁体   中英

Simple Linq query that joins two tables and returns a collection

I have two tables LookUpCodes and LookUpValues they are defined as below:

public partial class LookUpCodes
{
    public int Id { get; set; }
    public int? CodeId { get; set; }
    public string Code { get; set; }
    public string Description { get; set; }
}



public partial class LookUpValues
{
    public int Id { get; set; }
    public int CodeId { get; set; }
    public string CodeValue { get; set; }
    public bool? IsActive { get; set; }
}

Each LookUpCode can have multiple Values associated with it. I want to pass in a code and get associated list of values back.

This is probably a common question as I have seen this everywhere, I am not looking for an answer per se, if someone can just explain how to build the proper query I would be obliged.

Here is what I have done so far:

public IEnumerable<LookUpValues> GetValuesByCode(string cd)
{
    var query = from code in _context.LookUpCodes
                join values in _context.LookUpValues on code.CodeId equals values.CodeId
                where code.Code == cd
                select new { LookUpValues = values };
    return (IEnumerable<LookUpValues>) query.ToList();
}

You are very close to that you are looking for:

public IEnumerable<LookUpValues> GetValuesByCode(string cd)
{
    var query = from code in _context.LookUpCodes
                join values in _context.LookUpValues 
                on code.CodeId equals values.CodeId
                where code.Code == cd
                select values;

    return query;
}

Since you have written the join , I assume that you have understood how it works. However let's revisit it:

from a in listA
join b in listB
on a.commonId equals b.commonId

In the above snippet we join the contents of listA with the contents of listB and we base their join on a commonId property existing in items of both lists. Apparently the pair of a and b that fulfill the join criterion it would form one of the possible many results.

Then the where clause is applied on the results of the join. The joined items that pass the join. The joined items that pass the where filter is the new result. Even at this point the results is still pairs of filter is the new result. Even at this point the results is still pairs of a and b`.

Last you project, using the select keyword each pair of the results to a new object. In your case, for each pair of code and values that passed also the where filter, you return only the values .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM