限制GridView的LINQ的结果列 [英] Limit Linq result columns for GridView

查看:70
本文介绍了限制GridView的LINQ的结果列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的业务层,这种静态的方法,返回晚餐

 公共静态System.Collections.Generic.List<晚餐及GT; GetDinners()
{
    使用(DataClassesDataContext H =新DataClassesDataContext())
    {
        变种查询=(从h.Dinners DINS
                     其中,dins.Title ==纽约
                     选择喧嚣);
        返回query.ToList();
    }
}

我用这个在我的aspx页面来填充网格。

 保护无效的Page_Load(对象发件人,EventArgs的发送)
{
    GridView1.DataSource = BusinessLayer.GetDinners();
    GridView1.DataBind();
}

我想在业务层级别来限制返回的列。
我可以做的Linq这样。

  VAR的查询=(从喧嚣中h.Dinners
                     其中,dins.Title ==纽约
                     选择新的{dins.Title,dins.DinnerID});

但后来我得到一个匿名类型的错误,这是有道理的,但我怎么解决这个得到正确?

 无法隐式转换类型'System.Collections.Generic.List< AnonymousType#1>'至
System.Collections.Generic.List<晚餐及GT;


解决方案

您不能从方法返回匿名类型,除非返回类型是动态的。否则,你需要创建结果一个单​​独的类和项目,在你的SELECT语句。

无论是签名改为如下:

 公共静态System.Collections.Generic.List<动态> GetDinners()
{

和再回到您的查询像这样:

 返回query.ToList()演员LT;动态方式>()了ToList();

或者创建一个类,并返回该列表,而不是使用匿名类型。

I have this static method in my business layer for returning Dinners

public static System.Collections.Generic.List<Dinner> GetDinners()
{
    using (DataClassesDataContext h = new DataClassesDataContext())
    {
        var query = (from dins in h.Dinners
                     where dins.Title == "New York"
                     select dins);
        return query.ToList();
    }
}

I use this to populate a grid in my aspx page.

protected void Page_Load(object sender, EventArgs e)
{
    GridView1.DataSource = BusinessLayer.GetDinners();
    GridView1.DataBind();
}

I want to limit the returned columns at the business layer level. Which I can do in Linq like this.

        var query = (from dins in h.Dinners
                     where dins.Title == "New York"
                     select new { dins.Title, dins.DinnerID });

But then I get an anonymous type error, which makes sense, but how do I get around this correctly?

Cannot implicitly convert type 'System.Collections.Generic.List<AnonymousType#1>' to   
'System.Collections.Generic.List<Dinner>

解决方案

You can not return anonymous types from method unless the return type is dynamic. Otherwise you need to create a separate class for the result and project that in your select statement.

Either change the signature to as follows:

public static System.Collections.Generic.List<dynamic> GetDinners()
{

And then return your query like so:

return query.ToList().Cast<dynamic>().ToList();

Or create a class and return list of that instead of using Anonymous type.

这篇关于限制GridView的LINQ的结果列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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