How to use generic type with the database Context in EF6 Code First(如何在 EF6 Code First 中将泛型类型与数据库上下文一起使用)
问题描述
例如,假设我有 4 个不同的实体,每个实体都实现了将实体添加到数据库的 Add() 方法:
For example, let say I have 4 different entity that each implement a Add() method that add the entity to the database :
public class Profile
{
...
public void Add()
{
this._dbContext.Profile.Add(this);
this._dbContext.SaveChanges();
}
...
}
现在我想要一个通用类,在一个抽象类而不是 X 个类中实现这种行为.所以我尝试了以下方法:
Now I would like to have a generic class that implement this kind of behavior in one abstract class instead of X number of classes. So I tried the following :
public abstract class Entity<TEntity> where TEntity : class
{
protected DbContext _dbContext;
protected Entity()
{
this._dbContext = new SMTDBContext();
}
public void Add()
{
this._dbContext.Set<TEntity>().Add(this);
this._dbContext.SaveChanges();
}
}
当然它不起作用,因为this"不是 TEntity……但它会在未来出现!我尝试寻找迄今为止做过类似事情但没有成功的人.
Of course it doesnt worrk because "this" is not a TEntity... but it will be in the future! I tried searching for someone who did something similar without success so far.
推荐答案
解决问题的方法是更明确地定义泛型约束.将约束定义为 TEntity 必须是 Entitywhere TEntity : Entity
而不是 where TEntity : class代码>
The solution to your problem is to be more explicit with the definition of the generic constraint. Define the constraint as TEntity must be a sub-class of Entity<TEntity> i.e. use where TEntity : Entity<TEntity>
instead of where TEntity : class
public abstract class Entity<TEntity> where TEntity : Entity<TEntity>
{
protected DbContext _dbContext;
protected Entity()
{
this._dbContext = new SMTDBContext();
}
public void Add()
{
this._dbContext.Set<TEntity>().Add((TEntity)this);
this._dbContext.SaveChanges();
}
}
这篇关于如何在 EF6 Code First 中将泛型类型与数据库上下文一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 EF6 Code First 中将泛型类型与数据库上下文一起使用


- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- 如何用自己压缩一个 IEnumerable 2022-01-01
- 输入按键事件处理程序 2022-01-01