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

荒凉一梦 提交于 2019-12-04 02:32:22

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!