Asp.Net Core Generic Repository Pattern Soft Delete

Viewed 587

I'm trying to create a Soft Delete action in my Repository but i have to do that without creating any interfaces or classes. 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. 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. When i create a new object, it takes null value. That is why im controlling that property as ==null .

1 Answers

First you check if the property IsDelete is null, and then you try to set the value of the property which is, obviously, null.

if (model.GetType().GetProperty("IsDelete") == null ) should be

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