简体   繁体   English

是否可以创建一个将项添加到实体框架dbset的通用方法?

[英]Is it possible to create a generic method for adding items to a entity framework dbset?

I have not worked with Entity Framework or generics before and am having some difficulty reducing my code. 我之前没有使用Entity Framework或泛型,并且在减少代码方面遇到了一些困难。

I am parsing a text file to load 10 lookup tables with data that could possibly change nightly. 我正在解析一个文本文件来加载10个查找表,其中的数据可能会在每晚更改。 The text files have a heading for the "type" followed by a list of key/value sets. 文本文件具有“类型”的标题,后跟键/值集的列表。 I have this working perfectly, but I would like to refactor the code to clean it up and would like to use generic methods to accomplish this so I can reduce the duplicated code. 我有这个完美的工作,但我想重构代码来清理它,并希望使用泛型方法来实现这一点,所以我可以减少重复的代码。

I have gotten the parsing down to a generic method, but I have not been able to figure out how to get the entities added to the context in a generic way. 我已经解析为泛型方法,但我无法弄清楚如何以通用方式将实体添加到上下文中。 I have to loop over a list of the entities for each type and add them to the context: 我必须遍历每种类型的实体列表并将它们添加到上下文中:

void Main()
{
    switch (line.ToUpper())
    {
        case "AREA":
        {
            List<Area> areaList = this.GetItems<Area>(file);

            foreach (var element in areaList)
            {
                if (context.Area.Find(element.Id) == null)
                {
                    context.Area.Add(element);
                }
            }

            break;
        }
        case "CATEGORY":
        {
            List<Category> categoryList = this.GetItems<Category>(file);

            foreach (var element in categoryList)
            {
                if (context.Category.Find(element.Id) == null)
                {
                    context.Category.Add(element);
                }
            }

            break;
        }
    }
}

private List<T> GetItems<T>(StreamReader reader) where T : ILookupData, new()
{
    string line;
    List<T> list = new List<T>();            

    while (reader.Peek() == ' ')
    {
        line = reader.ReadLine().TrimStart();
        string[] tokens = line.Split(new string[] { " - " }, 2, StringSplitOptions.None);

        T item = new T();
        item.Id = Convert.ToInt32(tokens[0]);
        item.Description = (string)tokens[1];

        list.Add(item);
    }

    return list;
}

Update : The above works fine, but cannot seem to get the context added. 更新 :以上工作正常,但似乎无法获得上下文。

I have tried a few different things, but seem to keep getting this error when I try to generic up the context: 我尝试了一些不同的东西,但是当我尝试对上下文进行泛化时似乎仍然遇到此错误:

The type 'T' must be a reference type in order to use it as parameter 'T' in the generic type of method. 类型“T”必须是引用类型,以便在泛型类型的方法中将其用作参数“T”。

The last thing I tried was to add a generic GetDbSet to the context: 我尝试的最后一件事是在上下文中添加一个通用的GetDbSet:

public DbSet<T> GetDbSet<T>() where T : class
{
    return this.Set<T>();
}

But I get the same error in my controller adding this code to the GetItems method: 但是我在控制器中将此代码添加到GetItems方法时出现相同的错误:

using (MyContext context = new MyContext())
{
    var dbSet = context.GetDbSet<T>();
}

I have a generic repository in my current project. 我当前项目中有一个通用存储库。 This is its add method: 这是它的添加方法:

public void Add<T>(T newItem) where T : class
{
    db.Set<T>().Add(newItem);
}

where db is the DbContext object itself. 其中dbDbContext对象本身。 The where T : class fixes that error about reference types. where T : class修复了有关引用类型的错误。 Without it, you could pass any type in as T, including bool or struct , or any value type, which DbSet.Add() can't handle. 没有它,你可以传递任何类型为T,包括boolstruct ,或任何值类型, DbSet.Add()无法处理。 The where specifies that T must be a class, which is a reference type, and therefore allowed. where指定T必须是一个类,它是一个引用类型,因此允许。

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

相关问题 如何通过在实体框架中添加表来创建DbSet函数 - How to create DbSet function from adding a table in Entity framework 在迁移时在实体框架的dbset中使用通用时 - When using generic in the dbset of the entity framework at Migration 使用实体框架(DbSet)查询顶部子项 - query for top child items with Entity Framework (DbSet) 实体框架代码首先添加 DbSet 属性 - Entity Framework code first adding DbSet property 实体框架6模拟包括dbset上的方法 - Entity framework 6 mocking include method on dbset 创建一个数据库集<T>在实体框架中动态? - Create a DbSet<T> dynamically in Entity Framework? Entity Framework 7 创建 DbSet 的内存实现 - Entity Framework 7 Create in-memory implementation of DbSet 在实体框架中,如何在没有枚举所有可能 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? 如何在实体框架中将字符串作为类型DbSet的类型参数传递? - How to pass an string as a type parameter for a generic DbSet in Entity Framework? 实体框架:通过主键自动对通用DbSet进行排序 - Entity Framework: Automatically sorting generic DbSet by primary key
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM