locked
How to manage DataContext while implementing CompiledQuery in Entitity Framework 4.0? RRS feed

  • Question

  • Hello All,

    I have implemented Compiled Query in my project as follows.

    public static Func<Entities,int,IQueryable<UserLogin>> getUser = CompiledQuery.Compile((Entities context,int UserId) =>
                    (from user in context.UserLogin where user.UserID == UserId select user));


    this is simple compiled query. Now my concern begins with DataContext which need to pass while invoking compile query from code behind.

    public void GetAllUsers()
    {
      Entities entities = new Entities(); 
      var result = getUser(entities,5);
    
      foreach(User u in result)
      {
      }
    }

    By invoking above call we can get result using compiled query. But as specified in code that each time I am initialize Entities(DataContext) and pass into compiled query.

    If I am supplying new DataContext everytime then will it work for Compile query or benefit of Compiled Query performace will be avoided as I am supplying DataContext each time?

    so I my concern is how to manage Entities(DataContext) ? Should I make DataContext static and store it anywhere?

    Can u guide me ?

    Thanks in advance

    Dharmesh





    • Changed type dmsolanki Thursday, September 13, 2012 2:01 PM
    • Edited by dmsolanki Thursday, September 13, 2012 2:02 PM
    Thursday, September 13, 2012 12:23 PM

Answers

  • Hi Dmsolanki,

    Welcome to the MSDN forum.

    I think each time you call GetAllUers method the new instance of Entities will be initialized, which will reduce performance. You can make it static and read only like this:

        class Test
        {
            private static DataClasses1DataContext _context;
            public static DataClasses1DataContext context
            {
                get
                {
                    if (_context == null)
                    {
                        _context = new DataClasses1DataContext();
                    }
                    return _context;
                }
            }
            public static Func<DataClasses1DataContext, Int32, IQueryable<CompanyProduct>> getProduct = CompiledQuery.Compile((DataClasses1DataContext context, Int32 companyId) => (from p in context.CompanyProducts where p.CompanyID == companyId select p));
            public void GetProducts()
            {
                var result = getProduct(Test.context, 1);
    
                foreach (var p in result)
                {
                   Console.WriteLine(p.Name);
                }
            }
        }
    

    Good day.


    Alexander Sun [MSFT]
    MSDN Community Support | Feedback to us

    • Marked as answer by Alexander Sun Wednesday, September 19, 2012 7:17 AM
    Friday, September 14, 2012 7:09 AM