0

I want to implement business logic in DbSet derived classes. I like the idea of not having services and DAL abstractions and think this could be a good way. For this to work I need to inject objects into my DbSet but I don't know how. Here some sample code which does not work, because the EF Framework can't create an object of the DbSet. Maybe someone can point me in the right direction?

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
    This makes me a bit uncomfortable if I'm honest. You are now mixing your domain code with your business logic and sending mails. I'd keep them separated. – DavidG Oct 02 '15 at 10:41
  • I see. I changed the example to some other reference to not confuse that, because I more or less want to know how to inject anything there – user2595342 Oct 02 '15 at 11:17
  • The right direction is: back. Don't use DbSet for anythings else than what it's intended for. Whatever you're trying to achieve, there are better ways. – Gert Arnold Oct 04 '15 at 21:25

1 Answers1

0

One of the options is to aggregate real DbSet, not derive it:

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

Community
  • 1
  • 1
Ilya Chumakov
  • 23,161
  • 9
  • 86
  • 114