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 模态进度窗口 2022-01-01
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
- C# 从 List<List<int>> 中删除重 2022-01-01
- Moq It.Is<>不匹配 2022-01-01
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
- .NET SerialPort DataReceived 事件未触发 2022-01-01
