Create a DbSet dynamically in Entity Framework?

后端 未结 3 1737
鱼传尺愫
鱼传尺愫 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条回答
  • 2020-12-25 13:01

    DbContext has method for this:

      var set = context.Set<MyEntity>();
    
    0 讨论(0)
  • 2020-12-25 13:07

    Use:

    DbSet<MyEntity> set = context.Set<MyEntity>();
    

    Or, if you can't use the generic method:

    DbSet set = context.Set(
        typeof( MyEntity )
    );
    

    Don't worry about second-loading and duplicating a POCO. Sets are cached internally by the Context.

    0 讨论(0)
  • 2020-12-25 13:07

    This is my aproach:

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

    And you call this function as:

    List<Customer> lst = StaticClass.GetCollection<Customer>();
    

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

    0 讨论(0)
提交回复
热议问题