C# Entity Framework Basics Introducing Entity Framework Adding a Context

odalis garcia
odalis garcia
21,310 Points

I am stuck like a duck. Please help

Not too sure of what I am doing here.

Context.cs
using System.Data.Entity;

namespace Treehouse.CodeChallenges
{
    public class ContextDBEntities : DbContext
    {
    public CourseDBEntities()
    : base("name=CourseDBEntities")
    }
}
Course.cs
namespace Treehouse.CodeChallenges
{
    public class Course
    {
        public int Id { get; set; }
        public string Title { get; set; }
        public string Description { get; set; }
        public int Length { get; set; }
    }
}

1 Answer

Balazs Pukli
Balazs Pukli
46,033 Points

In order to be able to use your Context class to access your database, you have to define a property in it which represents for each table you are accessing. These properties need to have the DbSet<> type, which is really just a list of objects, representing the list of records in the database.

In this case, you have a Course data model, representing the Courses table in the database. This means, you need to define a property with the type DbSet<Courses>. From then on, Entity Framework will look for the model in you code and the table in the database with the corresponding names - this is very convenient for the developer, compared to database access methods from 10-20 years ago. But you must use the names properly in order to have Entity Framework do the job properly. (For example, the "Course" model is represented by the "Courses" or "Course" table in the database, and it is accessed by the "Courses" property in the context, which must be of DbSet type. These naming conventions make EntityFramework do its job well.)

public DbSet<Course> Courses {get; set;}