In Entity Framework, how can I add a generic object to the corresponding DbSet without a switch statement that lists all the possible DbSets?

I have two types of entities, an employee entity and an office entity, with a one-two 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 object:

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

      

The EF tutorial I did made me do my CRUD methods for a specific object. For example, the method below creates an office and adds it to an office DbSet (ignore the MVC stuff - I don't do 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, two things I want to emphasize are that the Office object is passed to this 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 that a generic object can be passed in and I can add it to its correct DbSet. The rough idea of ​​the method I have is something like this (I 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 to the Create method and he can see that it is Employee and so it will add it to the DbSet of Employees. I don't know if EF supports this. An alternative would be to make a switch statement, etc. Depending on the type of object being passed, I could directly call which DbSet should add the object. But I want to avoid this because I will be working with a lot more entities than just these two. Also I will have to do similar things for other CRUD methods.

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

+3


source to share


2 answers


You can think of a generic class as the following:



 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();
    }

  }

      

+7


source


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 type inference for you. You can just call it ...



db.Create(office);

      

... without having to worry about type. Of course, you must enter a known entity type.

+4


source







All Articles