本文介绍了如何在 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 必须是 Entity 的子类,即使用 where 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 中将泛型类型与数据库上下文一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-25 07:43