简体   繁体   中英

Linq to SQL join and group

I have two tables in my database:

Town:

userid, buildingid

Building:

buildingid, buildingname

What i want is to populate a GridView like this:

网格视图

But I don't want the buildings to be shown more than once. Here is my code:

var buildings = dc.Towns
            .Where(t => t.userid == userid)
            .GroupJoin(dc.Buildings,
                       t => t.buildingid,
                       b => b.buildingid,
                       (Towns, Buildings) => new
                                                {
                                                    BuildningName = Buildings.First().buildingname,
                                                    Count = Towns.Building.Towns.Count()
                                                });
        gvBuildings.DataSource = buildings.ToList();
        gvBuildings.DataBind();

New code which works:

var buildings = (from t in dc.Towns
                         where t.userid == userid
                         join b in dc.Buildings
                             on t.buildingid equals b.buildingid
                             into j1
                         from j2 in j1.DefaultIfEmpty()
                         group j2 by j2.buildingname
                         into grouped
                         select new
                                    {
                                        buildingname = grouped.Key,
                                        Count = grouped.Count()
                                    });
        gvBuildings.DataSource = buildings.ToList();
        gvBuildings.DataBind();
var buildings = from t in dc.Towns
join b in dc.Buildings on t.buildingid equals b.buildingid into j1
from j2 in j1.DefaultIfEmpty()
group j2 by b.buildingname into grouped
select new { buildingname = grouped.key, Count = grouped.Count()}

I think this should do it. I have not tested it so it might give error but it will be something like this.

Wouldn't something like this do it?

Users
    .Select(User => new {User, User.Building})
    .GroupBy(x => x.Building)
    .Select(g=> new {Building = g.Key, Count = g.Count()})

According to my experience with Linq to SQL, when the expression is becoming complicated it is better to write a stored procedure and call it with Linq to SQL. In this way you get better maintainability and upgradeability.

Rather than an option to pure SQL, I see “Linqu to SQL” as a tool to get hard typed object representation of SQL data sets. Nothing more.

Hope it helps you.

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