2

I am trying to use the new-ish Entity Framework 4.1 DbContext Generator because it generates very clean POCO classes for all of the entities, and it uses the DbContext API instead of the ObjectContext API. The problem I am having is that there appears to be no way to map "Function Imports" in the DbContext API (or at least using the generator). Is it not possible to use stored procedures for function imports with the DBContext API, or am I just doing something wrong?

Thanks

UPDATE I think that this is possible, but I would need to figure out how to get at the underlying ObjectContext of the DbContext API, anyone know how to do that at least?

samandmoore
  • 1,221
  • 2
  • 15
  • 23
  • Weird realization, it appears that if you force the solution to re-run the custom tooling (for the DbContext Generator) it will generate the proper stored procedure call. – samandmoore Apr 18 '11 at 18:21

2 Answers2

4

I went ahead with this approach:

  1. Generate the YourContext.Context1.cs file (using the DbContext Generator)
  2. Add this property to the partial class for YourContext:

    /// <summary>
    /// Retrieve the underlying ObjectContext
    /// </summary>
    public ObjectContext ObjectContext
    {
      get
      {
          return ((IObjectContextAdapter)this).ObjectContext;
      }
    }
    
  3. Set up your SPs in the .edmx using function import

  4. Add a function for each of your SPs to the YourContext class, e.g.

    public IEnumerable<SomeEntity> GetAllSomeEntities(Nullable<global::System.Int32> accountID)
    {
        ObjectParameter accountIDParameter;
        if (accountID.HasValue)
        {
            accountIDParameter = new ObjectParameter("accountID", accountID);
        }
        else
        {
            accountIDParameter = new ObjectParameter("accountID", typeof(global::System.Int32));
        }
    
        return this.ObjectContext.ExecuteFunction<SomeEntity>("GetAllSomeEntities", accountIDParameter);
    }
    
samandmoore
  • 1,221
  • 2
  • 15
  • 23
2

At least the Code-First approach of EF 4.1 doesn't support mapping to Stored Procedures:

Code First does not support mapping to stored procedures. However, you can call stored procedures directly by using ExecuteSqlCommand or SqlQuery. For example: context.Database.ExecuteSqlCommand("EXECUTE [dbo].[GetAllProducts]");.

But you seem to go Model-First/Database-First approach. I don't know if there is a solution. One could guess there is a way, since it is only said that Code-First doesn't support SP mapping.

And you can access the underlying ObjectContext from your dbContext instance this way:

ObjectContext objectContext = ((IObjectContextAdapter)dbContext).ObjectContext;
Slauma
  • 175,098
  • 59
  • 401
  • 420
  • yeah I am using DB-first, forgot to mention that in the initial post. This is the method I'm using now; adding more info in an answer of my own below. – samandmoore Apr 18 '11 at 18:06