In Entity Framework, how do I add a generic entity to its corresponding DbSet without a switch statement that enumerates all the possible DbSets?

后端 未结 2 623
感情败类
感情败类 2020-12-11 07:09

I have two types of entities: an employee entity and an office entity, with a one to many relationship between the two such that there are many employees for one office. For

相关标签:
2条回答
  • 2020-12-11 07:33

    You might consider a generic class like so:

     public class GenericRepository<T> where T : class
     {
        internal YourConext context;
        internal DbSet<T> dbSet;
    
        public GenericRepository(YourContext context)
        {
            this.context = context;
            this.dbSet = context.Set<T>();
        }
    
        public virtual void Insert(T entity)
        {
            dbSet.Add(entity);
            context.SaveChanges();
        }
    
      }
    
    0 讨论(0)
  • 2020-12-11 07:55

    If you have an extension method like...

    public static void Create<T>(this DbContext db, T entityToCreate)
        where T : class
    {
        db.Set<T>().Add(entityToCreate);
        db.SaveChanges();
    }
    

    ...C# will do the type inference for you. You can just call it as...

    db.Create(office);
    

    ...without ever having to worry about the type. Of course you should enter a known entity type.

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