如何在DbSet中使用DI

时间:2015-10-02 10:33:35

标签: entity-framework

我想在DbSet派生类中实现业务逻辑。我喜欢没有服务和DAL抽象的想法,并认为这可能是一个好方法。为此,我需要将对象注入我的DbSet,但我不知道如何。这里有一些示例代码不起作用,因为EF Framework不能创建DbSet的对象。也许有人可以指出我正确的方向?

public class LongTermBookingDbSet : DbSet<LongTermBooking>
{
    DbContext _dbContext { get; set; }

    public LongTermBookingDbSet(DbContext dbContext )
    {
        this._dbContext = _bContext ;
    }

    public override LongTermBooking Add(LongTermBooking entity)
    {
        return this.Add(entity, false);   
    }

    public LongTermBooking Add(LongTermBooking entity, bool SendMails)
    {
        var dbSet = base.Add(entity);

        //do something with the _dbContext

        return dbSet;
    }
}

1 个答案:

答案 0 :(得分:0)

其中一个选项是汇总真实DbSet,而不是派生它:

public class PersonSet : IDbSet<Person>
{
    private readonly DbSet<Person> _dbSet;

    public PersonSet(DbSet<Person> dbSet)
    {
        _dbSet = dbSet;
    }
}

public class MyDbContext: DbContext
{
    public PersonSet PersonSet {...}
}

Inherits from DbSet<T> with the purposes to add property

相关问题