简体   繁体   中英

how to get the max value of id from second table using join in entity framework in asp.net c#

I have two tables, from 1st table i want to get all records and from 2nd table i want the max id value of that record. I am using entity framework in asp.net c#.

i tried the below code but it takes only single record from first table ie tblblogs. and leave all the records, how to get all those records by using this query? plz help me out I'll be very grateful to you. Thanks !

     var query= (from c in db.tblBlogs join a in db.tblBlogMedias on c.id 
                  equals  a.BlogId where c.id==db.tblBlogMedias.Max(p=>p.id)

                        select new
                       {}

If I understood, you want to get an object with specific fields of Blogs and a list of tblBlogMedias.

You could try this code:

    var query2 = (from c in db.tblBlogs
    orderby c.Id descending
    group c.tblBlogMedias by new { c.Id, c.Name } into gb //It will show Id and name of tblBlogs, you can use more fields if you want 
    select new { 
        Id = gb.Key.Id,
        Name = gb.Key.Name, //I don't know if you have this field, but you should change it
        SecondTable = gb.ToList()
    })
    .OrderByDescending(o => o.Id) //this orderby with FirstOrDefault() replace where c.id==db.tblBlogMedias.Max(p=>p.id)
    .FirstOrDefault();

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