Return anonymous type from LINQ query?

2019-02-21 03:25发布

问题:

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>'

回答1:

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.

e.g.

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() {
...
}


回答2:

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

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