Object query in Entity Framework 6

4.7k views Asked by At

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

2

There are 2 answers

9
Stephen Brickner On BEST ANSWER

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);
0
sam On

---your code should look like this

string queryString = @"SELECT VALUE P FROM Tblproducts as P";

foreach (tblproducttype pt in cse.tblproducttypes)
{   
    ObjectContext context =((IObjectContextAdapter) cse).ObjectContext;
    ObjectQuery<tblproduct> filteredproduct = new ObjectQuery<tblproduct>(queryString, context);

    foreach (tblproduct tprod in filteredproduct)
    {
        Button b = new Button();
        b.Text = tprod.description;
        tp.Controls.Add(b);
    }
}