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 中将泛型类型与数据库上下文一起使用
基础教程推荐
- 重新排序 WPF TabControl 中的选项卡 2022-01-01
- 获取C#保存对话框的文件路径 2022-01-01
- 如果条件可以为空 2022-01-01
- C# 9 新特性——record的相关总结 2023-04-03
- Mono https webrequest 失败并显示“身份验证或解密失败" 2022-01-01
- SonarQube C# 分析失败“不是指针的有效行偏移" 2022-01-01
- 更新 Visual Studio 中的 DataSet 结构以匹配新的 SQL 数据库结构 2022-01-01
- 在 VB6 或经典 ASP 中使用 .NET 2022-01-01
- 从 C# 控制相机设备 2022-01-01
- 将数据集转换为列表 2022-01-01
