[英]Asp.Net Core Generic Repository Pattern Soft Delete
I'm trying to create a Soft Delete
action in my Repository
but i have to do that without creating any interfaces or classes.我正在尝试在我的
Repository
中创建一个Soft Delete
操作,但我必须在不创建任何接口或类的情况下这样做。 Let me show u to my method first,让我先告诉你我的方法,
public void Delete(T model)
{
if (model.GetType().GetProperty("IsDelete") == null )
{
T _model = model;
_model.GetType().GetProperty("IsDelete").SetValue(_model, true);//That's the point where i get the error
this.Update(_model);
}
else
{
_dbSet.Attach(model);
_dbSet.Remove(model);
}
}
im getting a Object reference not set to an instance of an object.
我得到一个
Object reference not set to an instance of an object.
exception.例外。 of course i know what that means but i just could not figure it out and i dont know what to do.
我当然知道那是什么意思,但我就是想不通,我不知道该怎么做。 I'm not sure if there is a better way or not.
我不确定是否有更好的方法。
Thanks for reading!谢谢阅读!
Guys u really gotta look at to the where i get the error.伙计们,你们真的要看看我得到错误的地方。 I'm editing my question.
我正在编辑我的问题。
public abstract class Base
{
protected Base()
{
DataGuidID = Guid.NewGuid();
}
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid DataGuidID { get; set; }
public int? CreatedUserId { get; set; }
public int? ModifiedUserId { get; set; }
public string CreatedUserType { get; set; }
public string ModifiedUserType { get; set; }
public DateTime CreatedDate { get; set; }
public DateTime? ModifiedDate { get; set; }
public bool? IsDelete { get; set; } //That's the property
}
Every type of model class is inheriting from that Base
class.每种类型的 model class 都继承自该
Base
class。 When i create a new object, it takes null value.当我创建一个新的 object 时,它需要 null 值。 That is why im controlling that property as
==null
.这就是为什么我将该属性控制为
==null
的原因。
First you check if the property IsDelete
is null, and then you try to set the value of the property which is, obviously, null.首先检查属性
IsDelete
是否为 null,然后尝试设置属性的值,显然是 null。
if (model.GetType().GetProperty("IsDelete") == null )
should be if (model.GetType().GetProperty("IsDelete") == null )
应该是
if (model.GetType().GetProperty("IsDelete") != null )
Edit:编辑:
Now we know that you want to check the value of a nullable bool, we have to take another approach.现在我们知道要检查可为空的布尔值,我们必须采取另一种方法。
// first we get the property of the model.
var property = model.GetType().GetProperty("IsDelete");
// lets assume the property exists and is a nullable bool; get the value from the property.
var propertyValue = (bool?)property.GetValue(model);
// now check if the propertyValue not has a value.
if (!propertyValue.HasValue)
{
// set the value
property.SetValue(model, true);
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.