我有一个包含此方法的通用存储库:
public void Delete<T>(T item) where T : EntityBase
我正在尝试向某些对象添加软删除行为; IE。删除后,它们不会从数据库中删除,而是将 bool Deleted
设置为 false
并且它们将停止显示在查询中,除非设置特定参数来包含它们。一般来说,应用程序的行为就好像它们不存在一样,但管理 View 除外,在管理 View 中可以通过再次翻转该 bool 值来恢复这些项目。我的问题是,在将对象传递给此方法时,它被作为 EntityBase 处理,它没有这种软删除行为,因为许多类不需要它。 SoftDeleteEntityBase 扩展了 EntityBase 类以添加软删除行为,但我找不到一种干净的方法来转换对象以便我可以获取 bool 值。我的第一个想法是:
public void Delete<T>(T item) where T : EntityBase
{
if (item is SoftDeleteEntityBase)
{
((SoftDeleteEntityBase)item).Deleted = true;
Update<T>(item);
}
else
{
db.Set<T>().Remove(item);
}
}
但这给了我错误“无法将类型 T 转换为 SoftDeleteEntityBase”
。
我如何获得这个 bool 值?
最佳答案
这个简短的解决方案怎么样,但请考虑更改存储库的设计
SoftDeleteEntityBase itemAsSoft = item as SoftDeleteEntityBase;
if (itemAsSoft != null)
{
itemAsSoft.Deleted = true;
Update(itemAsSoft);
}
我不知道你的背景,但是这个带有环绕泛型的解决方案怎么样
void Main()
{
Delete(new Base()); // called with base
Delete(new Derived()); //called with derived
}
public void Delete(Base item)
{
Console.WriteLine ("called with base");
//one logic
GenericDelete(item);
}
public void Delete(Derived item)
{
Console.WriteLine ("called with derived");
//another logic
GenericDelete(item);
}
public void GenericDelete<T>(T item)
{}
public class Base
{}
public class Derived : Base
{}
关于c# - 从一个通用方法传递对象,其中 T : MyClass to another where T : DerivedClass,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15688198/