Entity Framework Handson solutions cognizant

CourseRepository Entity Framework Cognizant Handson Solution

In this post, we are going to cover CourseRepository Handson which is asked under Entity Framework Topic in Cognizant Solutions.

Entity Framework Repository pattern

CourseRepository

Course.cs

//THIS CLASS IS FOR REFERENCE. YOU NEED NOT CHANGE
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Exercise1
{
    public class Course
    {
        public int CourseId { get; set; }
        public String CourseName { get; set; }
        public double CourseFee { get; set; }
        public int Duration { get; set; }
        public String InstructorName { get; set; }
    }
}

CourseContext.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Entity;

namespace Exercise1
{
    public class CourseContext : DbContext
    {
        public virtual DbSet<Course> Courses { get; set; }

        public CourseContext()
            : base("name=CourseConnectionString")
        { }
    }
}

Also Read : BookEntry_FluentAPI Entity Framework Cognizant Handson

CourseRepository.cs

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;

namespace Exercise1
{
    public class CourseRepository
    {
        private CourseContext context;

        public CourseRepository(CourseContext context)
        {
            this.context = context;
        }

        public IList<Course> GetCourseList() => this.context.Courses.ToList();

        public Course GetCourseByID(int courseId) => this.context.Courses.Find(courseId);

        public void InsertCourse(Course course)
        {
            this.context.Courses.Add(course);
            this.context.SaveChanges();
        }

        public Course UpdateCourseFee(int id, double fee)
        {
            var course = this.context.Courses.Single(c => c.CourseId == id);
            course.CourseFee = fee;
            this.context.SaveChanges();

            return course;
        }
    }
}

Program.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Exercise1
{
    public class Program
    {
        static void Main(string[] args)
        { }
    }
}

Similar Posts