简体   繁体   English

在实体框架中,如何在没有枚举所有可能 DbSet 的 switch 语句的情况下将通用实体添加到其对应的 DbSet?

[英]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:对于 EF,在上下文文件中为每个实体创建一个 DbSet:

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.我做的一个 EF 教程让我为特定实体做我的 CRUD 方法。 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):例如,下面的方法创建一个 office 并将其添加到 office DbSet(忽略 MVC 的东西——我不再这样做了):

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:基本上我想强调的两件事是将一个 Office 对象传递到方法中,并且通过显式编写 db.Offices 将 office 添加到 Office DbSet:

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.但是,我需要编写一个可以传入通用实体对象的方法,并且可以将其添加到其正确的 DbSet 中。 The rough idea for the method I have is something like this (I have ignored all the MVC stuff):我所拥有的方法的粗略想法是这样的(我忽略了所有 MVC 的东西):

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

So let's say I have an Employee object.所以假设我有一个 Employee 对象。 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.我可以将这个 Employee 传递给 Create 方法,它可以看到这是一个 Employee,因此它会将它添加到 Employees DbSet。 I don't know if EF supports this though.我不知道 EF 是否支持这一点。 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.另一种方法是创建一个 switch 语句,根据传入的实体类型,我可以直接调用哪个 DbSet 来添加实体。 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.此外,我将不得不为其他 CRUD 方法做类似的事情。

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.从 msdn 中看到了有关 ObjectSet.AddObject Method 的文档,看起来它应该很有用,但我不确定它是如何工作的。

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

  }

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. ...C# 会为你做类型推断。 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.当然,您应该输入已知的实体类型。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用Linq / Entity Framework将2个dbSet加入存储库关系请求中 - How do I join 2 dbSets in a repository relationship request using Linq / Entity framework 是否可以创建一个将项添加到实体框架dbset的通用方法? - Is it possible to create a generic method for adding items to a entity framework dbset? 如何在实体框架中将字符串作为类型DbSet的类型参数传递? - How to pass an string as a type parameter for a generic DbSet in Entity Framework? 在迁移时在实体框架的dbset中使用通用时 - When using generic in the dbset of the entity framework at Migration 实体框架核心:检查通用实体是否已存在于dbset中然后添加或更新的最快方法是什么? - Entity Framework Core: What is the fastest way to check if a generic entity is already in the dbset and then add or update it? 使用反射迭代实现接口的所有Entity Framework DbSet - Iterating all Entity Framework DbSets that implement an Interface using reflection 将DbSet <Entity>转换为其DbSet <IEntity>,而不将所有实体都拉入内存 - Casting DbSet<Entity> to its DbSet<IEntity> without pulling all entities to memory 使用实体框架,如何访问与每个办公室(另一个实体)相对应的雇员数量(一个实体)? - Using Entity Framework, how do I access the number of employees (one entity) corresponding to each office (another entity)? 在没有 DbSet 的情况下查询 Entity Framework Core - Querying Entity Framework Core Without DbSet 使用实体框架 dbset 获取所有行 - Get all rows using entity framework dbset
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM