简体   繁体   中英

Return anonymous type from LINQ query?

In that in business logic layer, I have created a class like this:

public List<roleHasRight> SelectAllData()
{
    try
    {
        return (from obj in Data.roleHasRights
                 join role in Data.roles on obj.FK_roleId equals role.roleId
                 select new
                 {
                     obj,
                     role.roleName
                 }).ToList();
    }
    catch
    {
        return null;
    }
}

So what would be my return type of SelectAllData method?

SelectAllData did not take List<roleHasRight> as return type it will give an error:

Cannot implicitly convert type System.Linq.IQueryable < AnonymousType#1>' to 'System.Linq.IQueryable < spaBL.roleHasRight>'

You are creating a new, anonymous Type by using:

select new { obj,role.roleName}

This type has 2 properties (the rolename and the roleHasRights object). In order to be able to return the same inforamtion by the method, you need to create a class with this information, or to return a dynamic.

eg

public class RoleHasRightInfo {
   public string Rolename {get;set;}
   public roleHasRight Right {get;set;}

}

and create it within the linq expression like this:

select new RoleHasRightInfo(){ Right=obj,Rolename = role.roleName}

The method would then need to return a List of this new type:

public List<RoleHasRightInfo> SelectAllData() {
...
}

If you return RoleHasRight you need to construct it, not an anonymous type as you do now:

select new RoleHasRight
{
    obj,
    role.roleName
}).ToList();

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