Ber*_*rip 2 c# asp.net entity-framework-core asp.net-core-mvc asp.net-core
我正在尝试在我的中创建一个Soft Delete操作Repository,但我必须在不创建任何接口或类的情况下执行此操作。首先让我向您展示我的方法,
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);
}
}
Run Code Online (Sandbox Code Playgroud)
我遇到了Object reference not set to an instance of an object.例外。我当然知道这意味着什么,但我就是不明白,也不知道该怎么办。我不确定是否有更好的方法。
谢谢阅读!
伙计们,你们真的必须看看我在哪里收到错误。我正在编辑我的问题。
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
}
Run Code Online (Sandbox Code Playgroud)
每种类型的模型类都继承自该类Base。当我创建一个新对象时,它采用空值。这就是为什么我将该财产控制为
==null.
首先检查该属性是否IsDelete为 null,然后尝试设置该属性的值,显然该值是 null。
if (model.GetType().GetProperty("IsDelete") == null )应该
if (model.GetType().GetProperty("IsDelete") != null )
编辑:
现在我们知道您想要检查可为空布尔值的值,我们必须采取另一种方法。
// 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);
...
}
Run Code Online (Sandbox Code Playgroud)