Creating LINQ to SQL Data Models' Data Contexts with ASP.NET MVC


I'm just getting started with ASP.NET MVC, mostly by reading ScottGu's tutorial. To create my database connections, I followed the steps he outlined, which were to create a LINQ-to-SQL dbml model, add in the database tables through the Server Explorer, and finally to create a DataContext class.

That last part is the part I'm stuck on. In this class, I'm trying to create methods that work around the exposed data. Following the example in the tutorial, I created this:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace MySite.Models
    public partial class MyDataContext
        public List<Post> GetPosts()
            return Posts.ToList();
        public Post GetPostById(int id)
            return Posts.Single(p => p.ID == id);


As you can see, I'm trying to use my Post data table. However, it doesn't recognize the "Posts" part of my code. What am I doing wrong? I have a feeling that my problem is related to my not adding the data tables correctly, but I'm not sure.

Thanks in advance.


Check the class name and namespace of your DataContext:

Is it MySite.Models.MyDataContext?

By : SDReyes

What's the name of your actual data context? Do you have a My.dbml file? Or is it named something different? The partial class definition has to exactly match the partial class definition given by the designer. Also, the partial class must be in the same project as the designer-generated class.

This video can help you solving your question :)
By: admin