向表添加实体的通用函数-实体框架6和C#



我正在尝试制作一个通用函数,这将有助于避免代码中的重复。函数必须是通用类型T(可能还有T2)的泛型,因为它必须引用正在创建的表中的不同字段。不过,我不知道这是否可能。

假设我有以下实体要添加到数据库中:

List<Type_1> entities_1 = new List<Type_1>()
{
    new Type_1{Field1="<Value of field 1",Field2="Value of Field 2", ...},
    new Type_1{Field1="<Value of field 1",Field2="Value of Field 2", ...},
    ...
    new Type_1{Field1="<Value of field 1",Field2="Value of Field 2", ...},
};
entities_1.ForEach(e => dbContext.Types_1.Add(e));
dbContext.SaveChanges();
entities_1 = null;
List<Type_2> entities_2 = new List<Type_2>()
{
    new Type_2{Field1="<Value of field 1",Field2="Value of Field 2", ...},
    new Type_2{Field1="<Value of field 1",Field2="Value of Field 2", ...},
    ...
    new Type_2{Field1="<Value of field 1",Field2="Value of Field 2", ...},
};
entities_2.ForEach(e => dbContext.Types_2.Add(e));
dbContext.SaveChanges();
entities_2 = null;
etc.

是否可以制作一个带有参数的函数:List<T1>dbContext引用T2,一个处理创建不同表的函数?也许这将需要参数化那些Type_(n)Types_(n)。我尝试了下面的东西,但编译器不接受它,并指向T2:

private void addEntitiesToDbContext<T1,T2>(List<T1> ent, MyTypeContext dbContext)
{
    ent.ForEach(e => dbContext.T2.Add(e));
    dbContext.SaveChanges();
}

谢谢



编辑:


我觉得我必须为在评论区占据空间而道歉

我刚刚意识到C Bauer对存储库模式所说的话。如果有人也对这个设计感兴趣,这里有一个很好的链接,我推荐:RepositoryPattern Explained。这里还有一个关于存储库模式设计的问题。祝你好运

PS。存储库模式的另一个非常好的来源

我希望这些能对你有所帮助。

public interface IRepository<TEntity>
    where TEntity : class
{
}
public abstract class RepositoryBase<TEntity> : IRepository<TEntity>
    where TEntity : class
{
    private DbContext dbContext;
    private DbSet<TEntity> dbSet;
    public IQueryable<TEntity> All
    {
        get
        {
            return dbSet;
        }
    }
    public void InsertOrUpdate(TEntity entity)
    {
    }
}
public class Repository<T> : RepositoryBase<T>
    where T : class
{
    public Repository(DbContext context)
    {
        DbContext = context;
        DbSet = context.Set<T>();
    }
}

我想不出为什么这不起作用:

1) 创建一个公共基类(或接口),称之为BaseEntity,所有实体都从中派生。

2) 将其添加到您的上下文类:

IDbSet<BaseEntity> Entitys { get; set; }

3) 让您的Add方法获取BaseEntity的列表

private void addEntitiesToDbContext(List<BaseEntity> ent, MyTypeContext dbContext)
{
    ent.ForEach(e => dbContext.Entitys.Add(e));
    dbContext.SaveChanges();
}

最新更新