Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

C# Entity Framework Basics Introducing Entity Framework Adding a Context

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 Peak
Balazs Peak
46,160 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;}