简体   繁体   中英

Error using a subset of fields in Entity Framework

I'm using EF 4 for the first time in a WebAPI service. I understand the basics if EF, but its still a bit of a learning curve when I'm used to using ADO.

I only want to return a subset (5) of over 100 fields in the table.

Model (EF Generated):

public partial class ITEM_MASTER
{
    public string IM_ITEM_CODE { get; set; }
    public string IM_UPC { get; set; }
    public string IM_SUBDEPARTMENT { get; set; }
    public string IM_DESC { get; set; }
    ...
}

Get Method in my Controller:

// GET api/Products
public IQueryable<ITEM_MASTER> GetProduct()
{
    // return db.ITEM_MASTER;

    return db.ITEM_MASTER.Select(x => new ProductList { ItemCode = x.IM_ITEM_CODE });
}

The return db.ITEM_MASTER works, but with the .Select method I get the error:

Cannot implicitly convert type 'System.Linq.IQueryable<JWebAPI.Models.ProductList>' to 'System.Linq.IQueryable<JWebAPI.Models.ITEM_MASTER>' . An explicit conversion exists (are you missing a cast?)

public class ProductList
{
    public string ItemCode {get; set;}
}

The ProductList class acts as a place holder object, as using the .Select returns a DBQuery not the original object type. I read that this was the ideal way to handle this situation. I'll add more properties to it when I've got it working. I have a downloaded sample that is structured the same way, and that works.

Is this the best way do do what I need, return only a subset of the EF fields? How can i resolve the conversion error?

Well the error is quite clear, your method is suppose to return IQueryable<ITEM_MASTER> but you are trying to return 'System.Linq.IQueryable<JWebAPI.Models.ProductList>' .

Since you projected your query's result to 'System.Linq.IQueryable<JWebAPI.Models.ProductList>' You need to have that as return type.

// GET api/Products
public IQueryable<ProductList> GetProduct() //Change return type
{
    // return db.ITEM_MASTER;

    return db.ITEM_MASTER.Select(x => new ProductList { ItemCode = x.IM_ITEM_CODE });
}

Since you are selecting only a subset of your original entity, you can't project to entity mapped to a table in Entity framework, that is why you need a place holder class ProductList

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM