Search code examples
c#databaseentity-frameworkentity

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


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 EF, a DbSet is created in the context file for each entity:

public DbSet<Office> Offices { get; set; }
public DbSet<Employee> Employees { get; set; }

An EF tutorial that I did had me do my CRUD methods for a specific entity. For example, the method below creates an office and adds it to the office DbSet (ignore the MVC stuff -- I am not doing that anymore):

public ActionResult Create([Bind(Include = "Address,BusinessName")] Office office)
    {
        try
        {

            if (ModelState.IsValid)
            {
                db.Offices.Add(office);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

        }
        catch (DataException /* dex */)
        {
            //Log the error (uncomment dex variable name and add a line here to write a log.
            ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator.");
        }
        return View(office);
    }

Basically the two things I want to emphasize is that an Office object is passed into the method, and that the office is added to the Office DbSet by explicitly writing db.Offices:

db.Offices.Add(office);

However, I need to write a method in which a generic entity object can be passed in, and I can add this to its correct DbSet. The rough idea for the method I have is something like this (I have ignored all the MVC stuff):

public void Create(object entityToCreate)
{
    db.CorrespondingEntityType.Add(entityToCreate);
    db.SaveChanges();
}

So let's say I have an Employee object. I can pass this Employee into the Create method and it can see that this is an Employee, and so it would add it to the Employees DbSet. I don't know if EF supports this though. An alternative would be to make a switch statement and that way depending on the type of the entity being passed in, I could directly call which DbSet to add the entity to. But I want to avoid that because I will be working with a lot more entities than just these two. Also I will be having to do similar things for the other CRUD methods.

I saw this documentation from msdn about the ObjectSet.AddObject Method, and it seems like it should be useful, but I'm not sure how it works.


Solution

  • You might consider a generic class like so:

     public class GenericRepository<T> where T : class
     {
        internal YourContext 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();
        }
    
      }