Download Free Demos

Scheduler .NET with Entity Framework Code First

There are three ways you can work with data in the Entity Framework:

This tutorial is dedicated for the Code First approach. Here you will find the information on how to start with an existing database and quickly create a simple event calendar in .NET 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

  • Name the new project "EventCalendarEFCodeFirst".

 event calendar code first

  • Select an Empty template and check the MVC option below the list of templates:

calendar creation code first

Step 2. Install Packages via NuGet

Right click on your project in the Solution Explorer and select Manage NuGet Packages.

It will open Manage NuGet Packages dialog box. Now select Online in the left bar and search for DHTMLX Scheduler .NET for ASP.NET:

install asp net calendar via nuget

After that find the EntityFramework package:

install entity framework via nuget

Step 3. Create a Controller and a 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 a 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 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, as in the example below:

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

Step 5. Add Possibility to Load and Save Data

At this stage we need to provide the data loading and saving functionality in the CalendarController.cs controller.

To enable loading and processing of data in Scheduler, add the code as in:

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

To enable data saving, add the required entities as follows:

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 of the CalendarController:

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's 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 an event, it’ll be successfully inserted into the database.

But, where is the database and what are the tables and its columns?

This is the beauty of the Code-First APIs of the Entity Framework. It creates a database based on the 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 has created the "EventCalendarEFCodeFirst.Models.CalendarContext" database in the local SQLEXPRESS database, as shown below.

 code first sqlexpress database

An event calendar with Entity Framework is ready.

Was this article helpful?

Yes No