Create a DbSet dynamically in Entity Framework?
DbContext has method for this: var set = context.Set<MyEntity>();
DbContext has method for this: var set = context.Set<MyEntity>();
Find calls DetectChanges internally, SingleOrDefault (or generally any query) doesn’t. DetectChanges is an expensive operation, so that’s the reason why Find is slower (but it might become faster if the entity is already loaded into the context because Find would not run a query but just return the loaded entity). If you want to use … Read more
This happens because of NSubstitute syntax specific. For example in: ((IQueryable<Blog>) mockSet).Provider.Returns(data.Provider); NSubstitute calls the Provider’s getter, then it specifies the return value. This getter call isn’t intercepted by the substitute and you get an exception. It happens because of explicit implementation of IQueryable.Provider property in DbQuery class. You can explicitly create substitutes for multiple … Read more
With Entity Framework Core (tested with Version 2.1) you can get the current context using // DbSet<MyModel> myDbSet var context = myDbSet.GetService<ICurrentDbContext>().Context; How to get a DbContext from a DbSet in EntityFramework Core 2.0
Set<T>() is already IQueryable<T> and it returns all rows from table public IQueryable<Company> GetCompanies() { return DbContext.Set<Company>(); } Also generated DbContext will have named properties for each table. Look for DbContext.Companies – it’s same as DbContext.Set<Company>()
DbContext has a method called Set, that you can use to get a non-generic DbSet, such as: var someDbSet = this.Set(typeof(SomeEntity)); So in your case: foreach (BaseEntity entity in list) { cntx.Set(entity.GetType()).Add(entity); }
myDbSet is not real implementation of DbSet but a mock which means it’s fake and it needs to be setup for all methods you need. The Add is not exception so it needs to be set up to do what you need otherwise it does nothing. Add something like the following and when the myDbSet.Add(“d”); … Read more