本文介绍了如何使用通用类型与数据库EF6代码中的上下文首先的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

例如,假设我有4个不同的实体,每个实体都会实现一个将实体添加到数据库的Add()方法:

  public class Profile 
{
...

public void Add()
{
this._dbContext.Profile.Add(this) ;
this._dbContext.SaveChanges();
}

...
}

现在我想有一个通用类,在一个抽象类中实现这种行为,而不是X个类。所以我尝试了以下内容:

  public abstract class Entity< TEntity>其中TEntity:class 
{
protected DbContext _dbContext;

protected Entity()
{
this._dbContext = new SMTDBContext();
}

public void Add()
{
this._dbContext.Set< TEntity>()。Add(this);
this._dbContext.SaveChanges();
}
}

当然不会因为这一个TEntity ...但它将在未来!

解决方案

您的问题的解决方案是更明确的通用约束的定义。定义约束作为 TEntity必须是Entity< TEntity> 的子类,即使用其中TEntity:Entity< TEntity> 而不是其中TEntity:class

  public abstract class Entity< TEntity>其中TEntity:实体< TEntity> 
{
protected DbContext _dbContext;

protected Entity()
{
this._dbContext = new SMTDBContext();
}

public void Add()
{
this._dbContext.Set< TEntity>()。Add((TEntity)this);
this._dbContext.SaveChanges();
}
}


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();
    }

    ...
}

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();
    }
}

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.

解决方案

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代码中的上下文首先的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-07 20:06