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 中将泛型类型与数据库上下文一起使用
基础教程推荐
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- 将 XML 转换为通用列表 2022-01-01
- 如何激活MC67中的红灯 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- rabbitmq 的 REST API 2022-01-01