Step 3. Adding a Model For Task Manager Data

Step 3. Adding a Model For Task Manager Data

Skip and go to the next step

The next step is to define a data model of our application and connect it to the database. As in the previous step, we'll be using Code First approach.

The following illustration shows the folder structure of the project:

 add model for task manager data

Step 3.1. Creating a Project

Your actions:

  1. Select SolutionAddNew Project → Your language → WindowsClass Library
  2. In the Name box, enter TaskManager.MVC5.Model
  3. In the Location box, enter a name for the project folder.
  4. Select Create directory for solution.
  5. Click Ok

Step 3.2. Adding Core Libraries

Add a package via Nuget(Package Manager Console):

Note: Please, check your Default Project in all installations of nuget packages:

 add core libraries

PM> Install-Package EntityFramework 

 install entity framework

Step 3.3. Updating App.Config

Add connectionStrings to the app.config file:

 <configuration>
<connectionStrings>
    <add name="TaskManagerString" connectionString="data source=(LocalDB)\v11.0;attachdbfilename=|DataDirectory|\TaskManager.mdf;integrated security=True;connect timeout=30;MultipleActiveResultSets=True;App=EntityFramework" providerName="System.Data.SqlClient" />
  </connectionStrings>
</configuration>

Step 3.4. Defining a Model and Context

  1. Add a New Folder with name Modelto the project
  2. AddNew Items into created folder (Status.cs, Task.cs, TaskManagerDbContext.cs)

Write two simple Status and Task entity classes as shown below:

  • Status.cs
namespace TaskManager.MVC5.Model
{
    using System.ComponentModel.DataAnnotations;
    using System.ComponentModel.DataAnnotations.Schema;
 
    [Table("Statuses")]
    public class Status    {
        public int id { get; set; }
        [StringLength(50)]
        public string title { get; set; }
 
        [StringLength(10)]
        public string color { get; set; }
    }
}
  • Task.cs
namespace TaskManager.MVC5.Model
{
    using System;
    using System.ComponentModel.DataAnnotations;
    using System.ComponentModel.DataAnnotations.Schema;
 
    public class Task
    {
        public int id { get; set; }
 
        [StringLength(256)]
        public string text { get; set; }
 
        public DateTime? start_date { get; set; }
 
        public DateTime? end_date { get; set; }
 
        [Column(TypeName = "text")]
        public string details { get; set; }
 
        public Guid? owner_id { get; set; }
 
        public Guid? creator_id { get; set; }
 
        public int? status_id { get; set; }
    }
}
  • TaskManagerDbContext.cs

We'll also override the seed method in order to show some initial statuses:

namespace TaskManager.MVC5.Model
{
    using System.Data.Entity;
 
    public class TaskManagerDbContext : DbContext
    {
        public TaskManagerDbContext()
            : base("name=TaskManagerString")
        {
        }
 
        public virtual DbSet<Status> Statuses { get; set; }
        public virtual DbSet<Task> Tasks { get; set; }
 
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Task>()
                .ToTable("Task");
 
            modelBuilder.Entity<Status>()
                .ToTable("Status");
        }
    }
 
    public class TaskManagerDbContextInit : CreateDatabaseIfNotExists<TaskManagerDbContext>
    {
        protected override void Seed(TaskManagerDbContext context)
        {
            InitTables(context);
            base.Seed(context);
        }
 
        private void InitTables(TaskManagerDbContext context)
        {
            /*
            if you need to create data tables
             */
            context.Statuses.AddRange(new[]
            {
               new Status(){title = "Waiting",color = "#5B9BE0"}, 
                new Status(){title = "In progress",color = "#FE7510"},
                new Status(){title = "Done",color = "#76B007"}
            });
        }
    }
}

Step 3.5. Creating a Repository

Repository pattern is an abstraction layer between the logic of your application and the implementation of database access. Your access layer can be any from ADO.NET stored procedures to EF. It also excludes duplicated code and simplifies testing.

1. Add aNew Item Interface named IRepository to the current project

2. Update the code as follows:

using System;
using System.Linq;
 
namespace TaskManager.MVC5.Model
{
    public interface IRepository : IDisposable
    {
        void Insert<T>(T entity) where T : class;
        IQueryable<T> GetAll<T>() where T : class;
        void Delete<T>(T entity) where T : class;
        void Update<T>(T entity) where T : class;
    }
}

3. Add New Item Class named Repository 4. DUpdate the code as follows:

using System.Data.Entity;
using System.Linq;
 
namespace TaskManager.MVC5.Model
{
    public class Repository : IRepository
    {
        private readonly TaskManagerDbContext context = new TaskManagerDbContext();
 
        public void Dispose()
        {
            context.Dispose();
        }
            public void Insert<T>(T entity) where T : class
        {
            if (entity == null) return;
            context.Entry(entity).State = EntityState.Added;
            context.SaveChanges();
        }
        public IQueryable<T> GetAll<T>() where T : class
        {
            return context.Set<T>();
        }
        public void Delete<T>(T entity) where T : class
        {
            if (entity == null) return;
            context.Entry(entity).State = EntityState.Deleted;
            context.SaveChanges();
        }
        public void Update<T>(T entity) where T : class
        {
            if (entity == null) return;
            context.Set<T>().Attach(entity);
            context.Entry(entity).State=EntityState.Modified;
            context.SaveChanges();
        }
    }
}

At the end Build Library and Add Reference to TaskManager.MVC5 site.

previous button step three next button


comments powered by Disqus