ev vk
ev vk

Reputation: 355

Entity Framework update field after a condition is met in an automated way

I am working with Entity Framework code-first and ASP.NET MVC in C#. I have a table:

public class Project
{
    public Guid Id { get; set; }
    public Guid UserId { get; set; }
    [Required]
    public DateTime CreationDate{ get; set; }
    [Required]
    public DateTime EndDate { get; set; }        
    [Required]
    public bool Active{ get; set; }

}

My question is, given the above fields, how do I update the Active field, after the EndDate passed?

For instance, the end date is 08/04/2018 and today is 08/05/2018, then Active=false.

Please take into account that performance is important in this case. Each user creates a project that other users can see.

Thank you.

Upvotes: 0

Views: 389

Answers (2)

EdSF
EdSF

Reputation: 12341

This isn't the only way. Use one that suits your needs/resources (what you have access to - e.g. SQL Server Agent). This takes things away from EF/application (everything in this sample is done in SQL Server).

A simplistic stored procedure could be:

// Expire after current date
UPDATE [insert your table name here] 
SET Active = 0 
WHERE DATEDIFF(DAY, EndDate, GETDATE()) > 0;

Yes, you can schedule a stored procedure to run as a JOB

So assuming you named the stored procedure UpdateStatus, your job command would be EXEC dbo.UpdateStatus.

Hth...

Upvotes: 2

Ugo Okoro
Ugo Okoro

Reputation: 164

Try making Active field a computed column.

[DatabaseGenerated(DatabaseGenerationOption.Computed)]
public bool Active { get { return [condition goes here]; } }

Upvotes: 1

Related Questions