Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
348 views
in Technique[技术] by (71.8m points)

c# - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

  }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...