Scheduler .NET with Entity Framework Code First

Scheduler .NET with Entity Framework Code First

There are three ways you can work with data in the Entity Framework: Model First, Database First and Code First. This tutorial is for Code First. We’ll create a simple event calendar in ASP.NET MVC with basic views and functionality like on the picture below:

 entity framework calendar code first

Step 1. Create an MVC Web Application

Open Visual Studio and create a new C# Web project named “EventCalendarEFCodeFirst”.

 event calendar code first

calendar creation code first

Step 2. Install packages via NuGet

Right click on your project in the Solution Explorer and select Manage NuGet Packages. This will open Manage NuGet Packages dialogue box. Now select Online in the left bar and search for DHTMLX Scheduler .NET for ASP.NET and EntityFramework as shown below.

install asp net calendar via nuget

install entity framework via nuget

Step 3. Create the Controller and View

At this step, create a controller and name it CalendarController.cs. It includes the default Index() method. Change the controller code to the following:

    public class CalendarController : Controller
    {
        public ActionResult Index()
        {
            var sched = new DHXScheduler(this);
            sched.Skin = DHXScheduler.Skins.Terrace;
            sched.LoadData = true;
            sched.EnableDataprocessor = true;
            sched.InitialDate = new DateTime(2016, 5, 5);
            return View(sched);
        }
    }

Right click the Views\Calendar folder and click Add, then click MVC 5 View Page with (Layout Razor). Add the following markup.

@{
    Layout = null;
}
 
<!DOCTYPE html>
<html>
<head>
    <title>DHXScheduler initialization sample</title>
    <style>
        body {
            background-color: #eee;
        }
    </style>
</head>
<body>
    <div style="height:700px;width:900px;margin:0 auto">
        @Html.Raw(Model.Render())
    </div>
</body>
</html>

Step 4. Create a Model

Instead of designing database tables first, let's start creating classes for our Calendar, as and when needed. First, we will create simple Event class.

public class Event
    {
        public int id { get; set; }
        public string text { get; set; }
        public string start_date { get; set; }
        public string end_date { get; set; }
    }

Create a context class as shown below, which derives from DBContext class and exposes DbSet properties for the types that you want to be part of the model, e.g. Event class, in this case.

public class CalendarContext : DbContext
    {
        public CalendarContext()
            : base()
        { }
 
        public DbSet<Event> Events { get; set; }
    }

Step 5. Manipulation with scheduler

At this stage we need to update the data load and save in the controller CalendarController.cs. Update data load and processing:

public ContentResult Data()
        {
            return (new SchedulerAjaxData(
                new CalendarContext().Events
                .Select(e => new { e.id, e.text, e.start_date, e.end_date })
                )
                );
        }

Add the required entities to enable data save:

 public ContentResult Save(int? id, FormCollection actionValues)
        {
            var action = new DataAction(actionValues);
            var changedEvent = DHXEventsHelper.Bind<Event>(actionValues);
            var entities = new CalendarContext();
            try
            {
                switch (action.Type)
                {
                    case DataActionTypes.Insert:
                        entities.Events.Add(changedEvent);
                        break;
                    case DataActionTypes.Delete:
                        changedEvent = entities.Events.FirstOrDefault(ev => ev.id == action.SourceId);
                        entities.Events.Remove(changedEvent);
                        break;
                    default:// "update"
                        var target = entities.Events.Single(e => e.id == changedEvent.id);
                        DHXEventsHelper.Update(target, changedEvent, new List<string> { "id" });
                        break;
                }
                entities.SaveChanges();
                action.TargetId = changedEvent.id;
            }
            catch (Exception a)
            {
                action.Type = DataActionTypes.Error;
            }
 
            return (new AjaxSaveResponse(action));
        }

Here is the full code:

 public class CalendarController : Controller
    {
        public ActionResult Index()
        {
            var sched = new DHXScheduler(this);
            sched.Skin = DHXScheduler.Skins.Terrace;
            sched.LoadData = true;
            sched.EnableDataprocessor = true;
            sched.InitialDate = new DateTime(2016, 5, 5);
            return View(sched);
        }
 
        public ContentResult Data()
        {
            return (new SchedulerAjaxData(
                new CalendarContext().Events
                .Select(e => new { e.id, e.text, e.start_date, e.end_date })
                )
                );
        }
 
        public ContentResult Save(int? id, FormCollection actionValues)
        {
            var action = new DataAction(actionValues);
            var changedEvent = DHXEventsHelper.Bind<Event>(actionValues);
            var entities = new CalendarContext();
            try
            {
                switch (action.Type)
                {
                    case DataActionTypes.Insert:
                        entities.Events.Add(changedEvent);
                        break;
                    case DataActionTypes.Delete:
                        changedEvent = entities.Events.FirstOrDefault(ev => ev.id == action.SourceId);
                        entities.Events.Remove(changedEvent);
                        break;
                    default:// "update"
                        var target = entities.Events.Single(e => e.id == changedEvent.id);
                        DHXEventsHelper.Update(target, changedEvent, new List<string> { "id" });
                        break;
                }
                entities.SaveChanges();
                action.TargetId = changedEvent.id;
            }
            catch (Exception a)
            {
                action.Type = DataActionTypes.Error;
            }
 
            return (new AjaxSaveResponse(action));
        }
    }

Finally, open RouteConfig.cs in the App_Start folder and update the controller route from 'Home' to 'Calendar' as it shown below:

 public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Calendar", action = "Index", id = UrlParameter.Optional }
            );
        }

If you run the application, you will be surprised to see that the application runs successfully and if you try to create event, it’ll successfully inserted into the database. But, where is the database and what are the tables and its columns? This is the beauty of Code-First APIs of Entity Framework. It creates the database based on parameter passed in the base constructor of your context class. Since we have not passed any parameter in the constructor of our context class, it created “EventCalendarEFCodeFirst.Models.CalendarContext” database in the local SQLEXPRESS database, as shown below.

 code first sqlexpress database

An event calendar with Entity Framework is ready.


comments powered by Disqus