【问题标题】:Asp.Net Core Generic Repository Pattern Soft DeleteAsp.Net Core 通用存储库模式软删除
【发布时间】:2021-07-25 20:12:21
【问题描述】:

我试图在我的Repository 中创建一个Soft Delete 操作,但我必须在不创建任何接口或类的情况下这样做。让我先告诉你我的方法,

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

我得到一个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
    }

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

【问题讨论】:

  • 使用!= null
  • 它没有任何意义,else 块总是工作,因为每个数据都有一个空值 IsDeleted 属性
  • 这意味着给定类型上没有这样的属性。范你发布完整的复制者,包括类型本身?
  • 我编辑了我的问题。

标签: c# asp.net asp.net-core entity-framework-core asp.net-core-mvc


【解决方案1】:

w首先检查属性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);
   ...
}

【讨论】:

  • 它没有意义,否则当我这样做时阻止总是工作。
  • 你确定IsDelete 是公开的并且是财产吗?
  • 是的,我确定,因为IsDelete 来自基类,每个类都继承自该类。
  • 我编辑了我的问题。我希望你能理解。
  • 更改了答案,希望对您有所帮助。
猜你喜欢
  • 1970-01-01
  • 2021-10-10
  • 1970-01-01
  • 2020-02-05
  • 2016-02-12
  • 1970-01-01
  • 2019-02-25
  • 2020-06-02
  • 2012-03-26
相关资源
最近更新 更多