如何以IQueryable< T>返回多个类 [英] How to return multiple classes as IQueryable<T>

查看:47
本文介绍了如何以IQueryable< T>返回多个类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Linq,我想返回一个包含客户及其发票的对象.

Using Linq I would like to return an object that contains customers and invoices they have.

我了解从方法返回单一类型:

I understand returning a single type from a method:

public IQueryable<customers> GetCustomers()
{
    return from c in customers
           select c;
}

但是我在找出多个对象时遇到了麻烦:

But I am having trouble figuring out multiple objects:

public IQueryable<???> GetCustomersWithInvoices()
{
    return from c in customers
           from inv in c.invoices
           select new {c, ci}  // or I may specify columns, but rather not.
}

我有种错误的感觉.目的是从控制器中调用这些对象,然后直接或使用formViewModel类将它们传递到视图.

I have a feeling I am approaching this the wrong way. The goal is to call these objects from a controller and pass them up to a view, either direct or using a formViewModel class.

推荐答案

在第二种情况下,您将创建一个具有方法范围的匿名类型.要在方法边界之外传递匿名类型,您需要将返回类型更改为object.但是,这违背了匿名类型的目的(因为您失去了它提供的强类型),需要进行反射才能访问所述类型的属性及其值.

In the second case you are creating an annonymous type which has method scope. To pass an annonymous type outside the method boundary you need to change the return type to object. This however defeats the purpose of the annonymous type (as you lose the strong typing it provides) , requiring reflection to get access to the properties and their values for the said type.

如果要将此结构保留为退货类型,则应创建一个由属性组成的类或结构,以保存客户和发票值.

If you want to maintain this structure as your return type you should create a class or struct consisting of properties to hold the customer and invoice values.

这篇关于如何以IQueryable&lt; T&gt;返回多个类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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