0

I am using entity framework. When I try to delete a row, I just want to change the value of its status field from 0 to 1 instead of deleting that row. For that, I just put some related code inside Delete action method on my Controller.

This is the Delete action method on my Controller:

public ActionResult Delete(int Id = 0)
{

        Register register = db.Registers.Create();
        register.RegisterId = Id;
        db.Registers.Attach(register);
        register.status = 1; 
        db.SaveChanges();
        return RedirectToAction("Index");

}        

This is working fine, if I didn’t use RequiredFieldValidation in my Model class named Register.cs. But after using RequiredFieldValidation, I’m getting this error:

"Validation failed for one or more entities. See 'EntityValidationErrors' property for more details." [InvalidOperationException: EmployeeAppMVC.Models.Register:First Name is required] [InvalidOperationException: EmployeeAppMVC.Models.Register:Last Name is required] [InvalidOperationException: EmployeeAppMVC.Models.Register:Phone No. is required] [InvalidOperationException: EmployeeAppMVC.Models.Register:EmailID is required]

This is my Register Class in Models:

public class Register
{
   public int RegisterId { get; set; }

   [Required(ErrorMessage = "First Name is required")]
   public string fname { get; set; }

   [Required(ErrorMessage = "Last Name is required")]
   public string lname { get; set; }

   [Required(ErrorMessage = "Phone No. is required")]
   [RegularExpression("^[0-9]{10}", ErrorMessage = "This phone number format is not recognised!!!")]
   public string phone { get; set; }

   [Required(ErrorMessage = "EmailID is required")]
   [RegularExpression(@"\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*", ErrorMessage = "Enter valid Email!")]
   public string email { get; set; }

   public int status { get; set; }
}

So, I want to turn RequiredFieldValidation off for these fields while executing Delete action method on my Controller.

Is there any way to do so? Or is there any other way to fix the error?

2
  • Short answer - you can't. But your code is not deleting anything - its just setting the value of property status. If you do want to just update a property of an existing entity, then get that entity from the db (based on the ID) and update it.
    – user3559349
    Nov 19, 2015 at 11:09
  • If all you need is the ID, then you need a (vew) model that only requires the ID to be set.
    – Richard
    Nov 19, 2015 at 13:26

3 Answers 3

0

There is no delete action performed in your code. You need to remove the record from the db and save the changes. Entity framework has remove method for doing the task. Please see the example code below.

    Student student = db.Students.Find(id);
    db.Students.Remove(student);
    db.SaveChanges();

You can also achieve the above result by marking the entity state as deleted. The SaveChanges method must issue a DELETE statement.

For update action please use the following example.

public ActionResult Update()
    {
        string studentId = Request.QueryString["stuId"].ToString();
        StudentManagerEntitie objentity = new StudentManagerEntitie();
        StudentDetail objstudentdetail = new StudentDetail();
        objstudentdetail = (from data in objentity.StudentDetails
                            where data.Id == studentId
                            select data).FirstOrDefault();

        _objstudentdetail .Id = studentId;
       objentity.SaveChanges();
    }
2
  • I don’t want to delete the record permanently. I just need to change the status from 0 to 1 when I click on delete link. Because, only those records whose status is 0 is displayed on the page.
    – Limna
    Nov 19, 2015 at 11:27
  • 1
    Then you need to go for update. On clicking the link update the value from 0 to 1 in db and the records with value of 1 will be ignored while displaying in the page.
    – BSG
    Nov 19, 2015 at 11:28
0

You can use a custom validation attribute rather than the out-of-box Required in your data annotations. In its IsValid method you can check the register object's status property and return isValid accordingly.

public class CustomAttribute : ValidationAttribute
{

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        var obj = object as Register;
        if(obj.Status == 1)
            return return ValidationResult.Success;
        //else perform additional check 
    }
}
0

I solved the error by updating the code inside Delete action method with the following code:

public ActionResult Delete(int Id = 0)
    {           
        Register register = db.Registers.Find(Id);
        register.status = 1;
        db.Entry(register).State = EntityState.Modified;
        db.SaveChanges();
        return RedirectToAction("Index");
    }       

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.