我有一个RepositoryBase类,它对从EntityBase派生的实体执行一些基本操作。
public class RepositoryBase
{
private ApplicationDbContext _context;
public DbSet<EntityBase> DbSet;
public RepositoryBase(ApplicationDbContext context )
{
_context = context;
}
public List<EntityBase> List(int entityStatus)
{
return DbSet.Where(a => a.EntityStatusId == entityStatus).OrderBy(a => a.Name).ToList();
}
public EntityBase GetTeamDetails(int id)
{
return this.DbSet.FirstOrDefault(a => a.Id == id);
}
internal List<EntityBase> ListActive()
{
return DbSet.Where(a => a.EntityStatusId == (int)EntityStatus.Active).ToList();
}
internal List<EntityBase> ListTrashed()
{
return DbSet.Where(a => a.EntityStatusId == (int)EntityStatus.Trashed).ToList();
}
public void SaveProject(EntityBase item)
{
DbSet.Attach(item);
_context.Entry(item).State = EntityState.Modified;
_context.SaveChanges();
}
public List<EntityBase> ListArchived()
{
return DbSet.Where(a => a.EntityStatusId == (int)EntityStatus.Archived).ToList();
}
internal List<EntityBase> Search(string searchText)
{
return DbSet.Where(a => a.Name.Contains(searchText)).ToList();
}
public EntityBase New(EntityBase item)
{
DbSet.Add(item);
_context.SaveChanges();
return item;
}
}
我遇到的问题是将DbSet传递给基类。这就是我想要做的事情:
public TeamRepository(ApplicationDbContext context) : base(context)
{
this.DbSet = (DbSet<EntityBase>)context.Teams;
}
但是,这不会编译。它说它不能从DbSet转换为DbSet,即使Team是从EntityBase派生的。
如何进行演员表?
答案 0 :(得分:1)
你不能这样做。你能做的是:
this.DbSet = context.Set<EntityBase>();
答案 1 :(得分:1)
你可以这样通用:
public class BaseRepository<T> : IBaseRepository<T> where T : EntityBase
{
public BaseRepository(CustomDBContext context)
{
if (context == null)
{
throw new ArgumentNullException("context", "The given parameter cannot be null.");
}
this.Context = context;
}
protected ApplicationDbContext Context
{
get;
private set;
}
public T Get(int id)
{
return Context.Set<T>().Find(id);
}
.....
}