【发布时间】:2014-04-24 04:56:02
【问题描述】:
我在实体框架中使用存储库模式,并且已经实现了一个通用存储库。
但对于某些类型的实体,我不想从数据库中删除记录,而是想将 IsDeleted 布尔值设置为 true。
为此,我创建了这个简单的界面:
IEntityProtectedDelete.cs
public interface IEntityProtectedDelete
{
bool IsDeleted { get; set; }
}
是这样在我的实体上实现的:
Queue.cs
public class Queue : IEntityProtectedDelete
{
public Queue()
{
IsDeleted = false;
}
[Key]
public int QueueId { get; set; }
[Required]
public string Name { get; set; }
[Required]
public bool IsDeleted { get; set; }
}
以下是我正在使用的通用存储库的一部分。 Delete 方法按预期工作,并在使用上述接口时将IsDelete 属性设置为 true。
但是,如果实体实现IEntityProtectedDelete,我不太清楚如何正确查询数据库。
GenericRepository.cs
public class GenericRepository<T> where T : class
{
protected DBContext context;
protected IDBSet dbSet;
public GenericRepository(IContext context)
{
this.context = context;
this.dbSet = context.Set<T>();
}
public virtual void Delete(T entity)
{
dbSet.Attach(entity);
if (entity is IEntityProtectedDelete)
{
(entity as IEntityProtectedDelete).IsDeleted = true;
context.Entry(entity).State = EntityState.Modified;
}
else { dbSet.Remove(entity); }
}
public virtual IEnumerable<T> GetAll()
{
if (typeof(IEntityProtectedDelete).IsAssignableFrom(typeof(T)))
{
return context.Set<T>().OfType<IEntityProtectedDelete>().Where(e => e.IsDeleted == false).ToList() as IEnumerable<T>;
}
else { return context.Set<T>().ToList(); }
}
}
在GetAll()方法中,OfType<>抛出异常:
'IEntityProtectedDelete' is not a valid metadata type for type filtering operations. Type filtering is only valid on entity types and complex types."
如果这不起作用,我还有什么其他选择?
【问题讨论】:
标签: c# linq entity-framework generics