Create a DbSet dynamically in Entity Framework?

后端 未结 3 1756
鱼传尺愫
鱼传尺愫 2020-12-25 12:33

In LINQ to SQL, I can create a repository dynamically using DataContext.GetTable. Is there a similar way to do this in Entity Framework 4 other than de

3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-25 13:07

    This is my aproach:

        public static List GetCollection()
        {
            List lstDynamic = null;
    
            using (MyDbContext db = new MyDbContext())
            {
                DbSet mySet = db.Set(typeof(T));
                mySet.Load();
                var list = mySet.Local.Cast();
    
                lstDynamic = list.ToList();
            }
            return lstDynamic;
         }
    

    And you call this function as:

    List lst = StaticClass.GetCollection();
    

    This returns your entire collection. I used this to perform a cache functionality for basic tables which don't change its content very often.

提交回复
热议问题