0

I'm a new beginner to the entity framework .

I try to write te following method but i get a compile time error.

 protected static void EntitySQLQuery(AWEntities context)
        {
            string cmd = @"SELECT VALUE c FROM AWEntities.Person AS c WHERE c.FirstName = @FirstName";

            ObjectQuery<Person> persons = new ObjectQuery<Person>(cmd, context);//Error


        }

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

Anyname Donotcare
  • 11,113
  • 66
  • 219
  • 392
  • 1
    The first argument looks good, so have you thought about if your `AWEntities` is really a `System.Data.Objects.ObjectContext` or not? According to the error text, the second argument of this constructor must be a `System.Data.Objects.ObjectContext`. – Jeppe Stig Nielsen Jan 27 '13 at 01:08
  • @JeppeStigNielsen :: the `AWEntities` is a public class inherit from `DbContext` – Anyname Donotcare Feb 02 '13 at 14:06
  • When you say `DbContext`, is that `System.Data.Entity.DbContext`? Because that class does not derive from `System.Data.Objects.ObjectContext` as required by the signature of the constructor. – Jeppe Stig Nielsen Feb 02 '13 at 14:50

2 Answers2

2

Your AWEntities context object is not recongnized as an ObjectContext. Please check the type of your object. Take a look at definition of ObjectContext and ObjectQuery's constructor

Yakup Ünyılmaz
  • 404
  • 3
  • 11
1

This is one of the more confusing points of Entity Framework. What you have to realize is that ObjectContext is the old way of doing EntityFramework, circa 2010. This was before DbContext (and code first). You can still get to the ObjectContext by casting your DbContext to IOjbectContextAdapter, like this:

((IObjectContextAdapter)context).ObjectContext;

Which would make your query look like this:

ObjectQuery<Person> persons = new ObjectQuery<Person>(cmd, ((IObjectContextAdapter)context).ObjectContext);

I do not know if Entity Structured Queries are promoted any more. I would consider using LInQ where possible.

var firstname = "Fred";
return from person in AWEntities.Person
       where person.FirstName = firstname
       select person;

If you are reading Julie Lerman's books, I would highly recommend that you pick up all three. The first one is a huge tomb explaining all of the fundamentals (and is written around the ObjectContext way of doing things), the second two are more practical to today's code-first/dbcontext world.

Phillip Scott Givens
  • 5,256
  • 4
  • 32
  • 54