Inherits from DbSet with the purposes to add property

后端 未结 4 547
太阳男子
太阳男子 2021-01-01 02:03

Is there a way to inherits from DbSet? I want to add some new properties, like this:

public class PersonSet : DbSet
{
    public int MyProperty         


        
4条回答
  •  一整个雨季
    2021-01-01 02:36

    One solution is to create a class that implements IDbSet and delegates all operations to a real DbSet instance, so you can store state.

    public class PersonSet : IDbSet
    {
        private readonly DbSet _dbSet;
    
        public PersonSet(DbSet dbSet)
        {
            _dbSet = dbSet;
        }
    
        public int MyProperty { get; set; }
    
        #region implementation of IDbSet
    
        public Person Add(Person entity)
        {
            return _dbSet.Add(entity);
        }
    
        public Person Remove(Person entity)
        {
            return _dbSet.Remove(entity);
        }
    
        /* etc */
        #endregion
    }
    

    Then in your DbContext, put a getter for your Custom DbSet:

    public class MyDbContext: DbContext
    {
        public DbSet People { get; set; }
    
        private PersonSet _personSet;
        public PersonSet PersonSet
        {
            get 
            {
                if (_personSet == null)
                    _personSet = new PersonSet( Set() );
    
                _personSet.MyProperty = 10;
    
                return _personSet;
            }
            set
            {
                _personSet = value;
            }
        }
    
    }
    

提交回复
热议问题