Kyle Humfeld February 2016

Entity Framework 6: getting the simple stuff to work

I've got a C#.NET (4.5.2) project that I'm trying to use Entity Framework (6.0) to manage my data model in a database. That's what EF is for, after all.

I followed the examples here: https://msdn.microsoft.com/en-us/data/ef.aspx

But they're all for EF 4.1, and none of the syntax in those examples is working for me. My conclusion is that something changed in the intervening versions, but I could be wrong; I've never used EF before, and since I'm able to get essentially nothing in it to work, I thought someone here might be able to point out what's probably an obvious error to an experienced eye.

First things first, I've got a Context class:

class DatabaseContext : DbContext
{
    public DbSet<Announcement> Announcements {get; set;}
}

And I've got a second class that tries to use that Context to grab data from my model.

public List<Announcement> AllAnnouncements {
    get{
        using (var db = new DatabaseContext())
        {
            var results = from a in db.Announcements select a;
            var records = results.ToList();
            return records;
        }
        return null;
    }
}

First problem: The db.Announcements in the second block has VS's red squiggly error line, and on hover, it says Could not find an implementation of the query pattern for source type 'DbSet<Announcement>'. 'Select' not found.

That tells me that the problem might be in the first block (where I set up the Context class), but if so I have no idea what it might be; I used the syntax in the documentation/examples, so I'm not sure what's correct if the docs are incorrecct.

Second problem: All of the examples I've found completely ignore the topic of ordering, but I want these records to be ordered in most-recent-firs

Answers


Shyju February 2016

VS is going to show the return null as unreachable code because you have a return statement before that. So just remove the return null part.

For ordering the records, you can use the orderby keyword in your LINQ statement.

var results = from a in db.Announcements orderby a.AnnouncementDate descending select a;

Post Status

Asked in February 2016
Viewed 2,613 times
Voted 10
Answered 1 times

Search




Leave an answer