简体   繁体   中英

how to select columns from two table with where using linq

I have three tables:

service_group
{
    id,
    title
}

service
{
    id,
    title,
    group_id
}

service_rate
{
    id,
    title,
    service_id,
    price,
    date
}

I have a combobox for group_service and user must select one and then open a form and user could have a choice from service_rate list. service_rate list includes all servic_rate with service_id in service.id which selected service_group_id .

Excuse me if I don't speak English well.

My code:

var list = (
  from p in db.Tbl_Services
  where p.Service_Group_ID == _service_group_id
  select new {
    p.ID,
    p.Title,
    p.Tbl_Services_Rate.Where(m = > m.Service_ID == p.ID).Last().Price,
    p.Tbl_Services_Rate.Where(m = > m.Service_ID == p.ID).Last().date
}).ToList();

but doesn't seem to work.

You can do something like this:

var list = db.Tbl_Services_Rate
    .Where(x=>x.service.group_id  == _service_group_id && x.service_id != null && x.service_id != "")
    .GroupBy(x=>x.service_id)
    .Select(x=>x.OrderByDescending(y=>y.id).FirstOrDefault())
    .ToList();

Null check is because you will remove those records that may contain service_id as null or empty since you will have to check by using this id.

var list = (from MM in service_rate join TL in service on MM.service_id equals TL.id
                           join Em in service_group on TL.group_id equals Em.id
                           where TL.group_id = 2 select new {
                               MM.id,
                               MM.title,
                               MM.service_id,
                               MM.price,
                               MM.date,
                           }).ToList();

You suppose to select all ID from Tbl_Service first and store in list / array. Then in second query use Contains to filter the IDs. Try below code.

var tblService = (from x in Tbl_Services where x.Service_Group_ID == "2" select x.ID).ToList();

var Tbl_Services_Rate = from y in Tbl_Services where tblService.Contains(y.Service_ID) select y;

Please try the below LINQ query,

from sr in  service_rate
               join s in service on sr.service_id equals s.id
               join sg in service_group on s.group_id  equals sg.id
               where sg.id==2
               select new 
    {sr.id,
        sr.title,
        sr.service_id,
        sr.price,
        sr.date}

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