开发者

How the return type is determined in a method that uses Linq2Sql?

I've usually have difficulties with return types when it comes to linq. I'll explain by the following examples. Let's say I have a Table Products with ProductID, Name, Category, and Price开发者_运维知识库 as columns :

1) IQueryable<***Product*>**

public IQueryable<Product> GetChildrenProducts()
{
  return (from pd in db.Products
          where pd.Category == "Children"
          select pd);
}

2) Product

public Product GetProduct(int id)
{
  return (from pd in db.Products
          where pd.ProductID == id
          select pd).FirstOrDefault();
}

Now, if I decide to select, for instance, only one column (Price or Name) or even 2 or 3 columns (Name and Price), but in any case, less than the 4 columns, what's going to be the return type?

I mean this:

public returnType GetSomeInformation()
{
 return (from pd in db.Products
         select new { pd.Name, pd.Price }
}

What SHOULD BE the returnType for the GetSomeInformation()?

Thanks for helping


You cannot use var in this context, since type can currently only be inferred in local variables.

So either:

Move the Select() part to the caller, and return a plain IQueryable<Product>:

public IQueryable<Product> GetSomeInformation()
{
  return (from pd in db.Products
          select pd);
}

var information = GetProductInformation().Select(p => new { p.Name, p.Price });

Create a returntype ProductInformation which only contains the information you need:

class ProductInformation
{
  public string Name { get; set; }
  public decimal Price { get; set; }
}

public IQueryable<ProductInformation> GetSomeInformation()
{
  return (from pd in db.Products
          select new ProductInformation { Name=pd.Name, Price=pd.Price });
}


If you select multiple columns, but not the full object, LINQ returns a generic object. If you want to return that subset of data via a function, you need to create your own class and load it like this:

public class MyObject
{
  public string Name { get; set; }
  public double Price { get; set; }
}

public MyObject GetSomeInformation()
{
 return (from pd in db.Products
         select new  MyObject {
           Name = pd.Name, 
           Price = pd.Price 
         }).FirstOrDefault();
}


Short answer: IEnumerable.

Long answer:

What you are returning is a collection of anonymous type, hence the need that the return type to be IEnumerable.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜