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 625
感情败类
感情败类 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 where T : class
     {
        internal YourConext context;
        internal DbSet dbSet;
    
        public GenericRepository(YourContext context)
        {
            this.context = context;
            this.dbSet = context.Set();
        }
    
        public virtual void Insert(T entity)
        {
            dbSet.Add(entity);
            context.SaveChanges();
        }
    
      }
    

提交回复
热议问题