简体   繁体   中英

Cannot implicitly convert type DbSet<> to IQueryable<>

I'm created an oData in ASP.NET WEB API using from this documentation. OData in ASP.NET Web API . My EF is on another project so I just add the reference to my WEB API project. Upon creating my endpoints.

    public class ItemController : ODataController
{
    SAP_PORTALEntities db = new SAP_PORTALEntities();
    private bool ItemExists(string key)
    {
        return db.sap_item.Any(s => s.ItemCode == key);
    }
    protected override void Dispose(bool disposing)
    {
        db.Dispose();
        base.Dispose(disposing);
    }

    [EnableQuery]
    public IQueryable<Item> Get()
    {
        return db.sap_item;
    }

    [EnableQuery]
    public SingleResult<sap_item> Get([FromODataUri] string key)
    {
        var item = db.sap_item.Where(s => s.ItemCode == key);
        IQueryable<sap_item> itemModel;

        itemModel = item;

        return SingleResult.Create(itemModel);
    }

    public async Task<IHttpActionResult> Post(sap_item item)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }
        db.sap_item.Add(item);
        await db.SaveChangesAsync();

        return Created(item);
    }
}

Got an error on this line: IQueryable Get()

Cannot implicitly convert type 'System.Data.Entity.DbSet<sap_dataaccess.sap_item>' to 'System.Linq.IQueryable<sap_portal.Models.Item>'. An explicit conversion exists

While the Item is my Model.

public class Item
{ 
    public string ItemCode { get; set; }
    public string Dscription { get; set; }
    public string ItemGroup { get; set; }
    public string InvItem { get; set; }
    public string PurItem { get; set; }
    public string SalItem { get; set; }
    public string UOMGroup { get; set; }
    public string Manufacturer { get; set; }
    public string Active { get; set; }
    public string PurUOM { get; set; }
    public Nullable<decimal> QtyPurUOM { get; set; }
}

You can try to use linq AsQueryable otherwise you will only return DbSet<sap_dataaccess.sap_item> that will be converted type fail.

[EnableQuery]
public IQueryable<Item> Get()
{
    return db.sap_item.AsQueryable();
}

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