Search code examples
c#entity-framework-6.1objectquery

Object query in Entity Framework 6


I'm getting an error with the ObjectQuery method, can someone help?

private void AddProductsToTabbedPanel()
        {
            foreach (TabPage tp in tabControl1.TabPages )
            {
                ObjectQuery<TblProduct> filteredProduct = new ObjectQuery<TblProduct>("Select value p from TblProduct as P", csdbe);

                foreach (TblProduct tpro in filteredProduct)
                {
                    Button btn = new Button();
                    btn.Text = tpro.Description;
                    tp.Controls.Add(btn);
                }
            }
        }

my logic here is that it adds button in control tab based on what is the content of TblProduct

But I got an error:

Argument 2: cannot convert from 'Coffee_Shop.CoffeeShopDatabaseEntities' to 'System.Data.Entity.Core.Objects.ObjectContext'

The best overloaded method match for 'System.Data.Entity.Core.Objects.ObjectQuery.ObjectQuery(string, System.Data.Entity.Core.Objects.ObjectContext)' has some invalid arguments


Solution

  • To start the true problem here is using entity framework as a way to run your sql code, this is not what entity framework is for. If you have entity framework attached to your database just do this to get your entities:

    //assuming csdbe is your data context
    var filteredProduct = csdbe.TblProduct;
    

    In your example above you are not filtering your query, just asking for all of them. To filter the example above use .Where

    var filteredProduct = csdbe.TblProduct.Where(x => x.SomeValue == "yourValue");
    

    Now for your original question:

    Argument 2: cannot convert from 'Coffee_Shop.CoffeeShopDatabaseEntities' to 'System.Data.Entity.Core.Objects.ObjectContext'

    It Appears by the exception you are getting that "csdbe" is a "CoffeeShopDatabaseEntities" entity. The second parameter required is a data context.

    var filteredProduct = new ObjectQuery<TblProduct>("SELECT VALUE P FROM TblProducts AS P", yourContext);