返回从LINQ查询匿名类型? [英] Return anonymous type from LINQ query?

查看:175
本文介绍了返回从LINQ查询匿名类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在在业务逻辑层,我创建了一个类是这样的:

 公开名单< roleHasRight> SelectAllData()
{

{
回报(从OBJ在Data.roleHasRights
加入Data.roles角色上obj.FK_roleId等于role.roleId
选择新的
{
OBJ,
role.roleName
})了ToList()。
}

{
返回NULL;
}
}



那么,什么将是我的返回类型 SelectAllData 方法?



SelectAllData 没有采取列表< roleHasRight> 的返回类型,它会给一个错误:




无法隐式转换类型System.Linq的.IQueryable<
AnonymousType#1>'到'System.Linq.IQueryable< spaBL.roleHasRight>



解决方案

您通过使用创建一个新的,匿名类型:

 选择新的{OBJ,role.roleName} 

这类型有2个属性(该角色名和roleHasRights对象)。
为了能够通过该方法返回相同的inforamtion,你需要创建一个类信息,或返回动态。



 公共类RoleHasRightInfo {
公共字符串ROLENAME {获取;集;}
公共roleHasRight右{得到;设置;}

}

和像LINQ表达式中创建这样的:

 选择新RoleHasRightInfo(){右= OBJ,角色名= role.roleName} 

然后该方法将需要返回这个新类型的列表:

 公开名单< RoleHasRightInfo> SelectAllData(){

}


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.

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

这篇关于返回从LINQ查询匿名类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆