简体   繁体   中英

How to choose specific DbSet from context by name

I have a bunch of DbSets that have the same structure so I can call them all as MyObject . In my EntityFramework I have a lot of entities that look the same, but have some other meaning. All entity types have 6 column/fields (the same).

Now, how can I choose the proper set from context basing only on DbSet name?

context.Set(Type type)

is not OK, because I can't call LINQ for Entities with it as long as I need a specific DbSet<OneOfEntities> .

Something missing?

UPDATE:

I've come up with idea of getting entities info by using reflecion but it seems to be a dead end as well, because still I can't determine from code the specific datatype for each of entities. Even when I have the table name, ex. MyObject and another MyObject2 , MyObject3 , etc. I can't transform it to the class which is defined in EDMX model. I tried something with Type.GetType() mixed with assemblies or by concatenating class name (table name) to namespace in one string. Still nothing.

Use a generic repository approach. Check this example out: https://docs.microsoft.com/en-us/aspnet/mvc/overview/older-versions/getting-started-with-ef-5-using-mvc-4/implementing-the-repository-and-unit-of-work-patterns-in-an-asp-net-mvc-application

Basically, you have something like this:

public class GenericRepository<TEntity> where TEntity : class
{
    internal SchoolContext context;
    internal DbSet<TEntity> dbSet;

    public GenericRepository(SchoolContext context)
    {
        this.context = context;
        this.dbSet = context.Set<TEntity>();
    }
    //Other code
}

I have used this approach for years, and it works awesome!! That way you are not tied to EF. Remember, you have to wrap your classes so you don't get stuck on a framework. The .NET Core EF is very different, and the upgrade would be very hard without a wrapper.

I noticed your comment about the entities having the same properties. I would use an abstract class like this:

public abstract class EntityBase
{
     //Add properties
}

Then make your entity inherit from this class:

public class MyExampleClass : EntityBase
{
     //Add other properties
}

Finally, change the GenericRepository to for TEntity to be a type of EntityBase:

public class GenericRepository<TEntity> where TEntity : EntityBase
{
    //Reference code from example
}

I have used this before and it works great!

~Cheers

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM