gpt4 book ai didi

c# - Asp.Net Core 通用存储库模式软删除

转载 作者:行者123 更新时间:2023-12-02 02:14:09 25 4
gpt4 key购买 nike

我正在尝试在我的存储库中创建一个软删除操作,但我必须在不创建任何接口(interface)或类的情况下执行此操作。让我先向您展示我的方法,

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);
}
}

我收到一个对象引用未设置到对象实例。异常。我当然知道这意味着什么,但我就是不明白,也不知道该怎么办。不知道有没有更好的办法。

感谢您的阅读!

伙计们,你们真的必须看看我收到错误的地方。我正在编辑我的问题。


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
}

每种类型的模型类都继承自该Base 类。当我创建一个新对象时,它采用空值。这就是为什么我控制该属性(property)==null .

最佳答案

首先检查属性 IsDelete 是否为 null,然后尝试设置该属性的值,显然该值是 null。

if (model.GetType().GetProperty("IsDelete") == null ) 应该是

if (model.GetType().GetProperty("IsDelete") != null )

编辑:

现在我们知道您想要检查可为空 bool 值的值,我们必须采取另一种方法。

// 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);
...
}

关于c# - Asp.Net Core 通用存储库模式软删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67368536/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com