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

前端 未结 1 1124
滥情空心
滥情空心 2021-02-19 09:23

I have not worked with Entity Framework or generics before and am having some difficulty reducing my code.

I am parsing a text file to load 10 lookup tables with data th

1条回答
  •  太阳男子
    2021-02-19 09:43

    I have a generic repository in my current project. This is its add method:

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

    where db is the DbContext object itself. The where T : class fixes that error about reference types. Without it, you could pass any type in as T, including bool or struct, or any value type, which DbSet.Add() can't handle. The where specifies that T must be a class, which is a reference type, and therefore allowed.

    0 讨论(0)
提交回复
热议问题