Moshhegh Faghdan
Moshhegh Faghdan

Reputation: 53

Best way to doing database task automatically in ASP.NET MVC 5 and EF

i have OnlineCourse entity that have StartDate and EndDate property

i want to deny user if current datetime is between StartDate and EndDate
or disable this course based on today date time

i put below code in my Register ActionMethod

var startDate = currentOnlineCourse.StartDate
var endDate = currentOnlineCourse.EndDate

if (endDate >= DateTime.Now)
{
   currentOnlineCourse.Enable = false;
   dbContext.SaveChanges();
   ViewBag.Message = "You cannot apply this Course");
   return View();
}  

my project contain many of this situation that need to preform some task(delete update ) database automatically
i want to create something like task scheduler and put this code in separate class and call it each date(ex 12:00 am of each day)
what is best way to do this??

Upvotes: 1

Views: 81

Answers (1)

Georg Patscheider
Georg Patscheider

Reputation: 9463

I like to handle custom validation logic by implementing IValidatableObject on the ViewModel:

public class OnlineCourseViewModel : IValidatableObject {
    public Datetime StartDate { get; set; }
    public Datetime EndDate { get; set; }
    public bool Enable { get; set; }

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) {
        if (EndDate > DateTime.Now) {
             yield return new ValidationResult(
                 "You cannot apply this Course",
                 new [] { "EndDate" }
             );
        }
    }
}

In your controller, check whether the model is valid:

[HttPost]
public ActionResult Submit(OnlineCourseViewModel postData) {

     if (!ModelState.IsValid) {
         // Validation failed -> show errors
         return View("Submit", postData);
     }

     // Validation succeeded
     // do your stuff ...
}

In your View, render any validation errors:

@model OnlineCourseViewModel 

@Html.ValidationSummary()

Upvotes: 1

Related Questions