开发者

Is there any way to get Function Import support while using DbContext Generator?

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 pro开发者_如何学Pythonblem 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?


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);
    }
    


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;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜