Click here to Skip to main content
15,886,033 members
Articles / Desktop Programming / WPF

EF Code First and WPF with the Chinook database. Part 1b – the provider

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
20 Jan 2011CPOL2 min read 10.6K   4  
EF Code First and WPF with the Chinook database. Part 1b – the provider

I like to isolate my data access code to a single point so that my client does not have to worry about creating contexts or anything of the sort. This makes it simpler to change the way the data is delivered to the client as it is abstracted away.

In thinking about what methods I would need for this, I discovered that for the first phase I would only need two:

  • GetArtists() – Returns all artists
  • SearchArtists(string searchTerm) – Searches for artists and returns any matches

I don't need any methods at the moment to fetch albums or tracks because I have virtual lazy loading properties set up to deal with them. I will be adding more methods to this provider as the series grows (such as adding, deleting,… etc.).

Let's go ahead and test those lazy properties:

C#
class Program
{
    static Chinook db = new Chinook();

    static void Main(string[] args)
    {
        // Using ToList() executes the command so the datareader is closed.
        var artists = db.Artist.ToList();
        foreach (var a in artists)
        {
            Console.WriteLine(a.Name);
            PrintAlbums(a.Albums);
        }

        Console.ReadLine();
    }

    static void PrintAlbums(ICollection<Album> albums)
    {
        foreach (var a in albums)
        {
            Console.WriteLine("\t" + a.Title);
            PrintTracks(a.Tracks);
        }
    }

    static void PrintTracks(ICollection<Track> tracks)
    {
        foreach (var t in tracks)
        {
            Console.WriteLine("\t\t" + t.Name);
        }
    }
}

image

Whoops – seems we have an invalid column name “ArtistArtistId”.

This is due to the way Code First decides on what the foreign key columns are called if we don’t explicitly include them – the default is “{TypeName}{TypeName}Id” which we obviously don’t have in the database.

We need to add the foreign key properties to our objects so EF picks up the correct names (this needs to be done for both Album and Track – note the new ArtistId and AlbumId respectively):

C#
public class Album
{
    public int AlbumId { get; set; }

    public string Title { get; set; }

    public int ArtistId { get; set; }

    public virtual Artist Artist { get; set; }

    public virtual ICollection<Track> Tracks { get; set; }
}

public class Track
{
    public int TrackId { get; set; }

    public string Name { get; set; }

    public int AlbumId { get; set; }

    public virtual Album Album { get; set; }

    public string Composer { get; set; }
}

We can now run our demo and get a correct output:

image

We are now in a position to implement our simple data provider.

I am going to put the data provider behind an interface to allow for easy extension and dependency injection should we want to go that way.

C#
public interface IDataProvider
{
    List<Artist> GetArtists();

    List<Artist> SearchArtists(string searchTerm);
}

This is then implemented as follows for the code first model:

C#
public class EFCodeFirstDataProvider : IDataProvider
{
    private Chinook db = new Chinook();

    public List<Artist> GetArtists()
    {
        return this.db.Artist.ToList();
    }

    public List<Artist> SearchArtists(string searchTerm)
    {
        return this.db.Artist.Where(a => a.Name.Contains(searchTerm)).ToList();
    }
}

We have a private instance of the Chinook data context that controls all of the fetching of data. When the Artist requests its albums, then this context is used. This is the same with the tracks.

The intention here is to allow the client to call simple methods to interact with the data and we are able to swap out for another provider if we so wish easily.

The only thing we now need to change is the little test app so that it uses the new data provider (we will hard code the type here but will be using dependency injection in our WPF app).

C#
static IDataProvider dp = new EFCodeFirstDataProvider();

static void Main(string[] args)
{
    var artists = dp.GetArtists();
    foreach (var a in artists)
    {
        Console.WriteLine(a.Name);
        PrintAlbums(a.Albums);
    }

    Console.ReadLine();
}

And that’s all there is to it – we now have a separate data provider to work with our entity framework objects.

The next part of this series (1c) is going to involve writing unit tests for the data provider. This is easier said than done and involves much mocking of the EF classes.


License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
United Kingdom United Kingdom
I am a developer currently working for a financial company in the UK with a focus on back end work using NServiceBus. Personally I also enjoy working with ASP.NET (MVC), WPF, ruby and investigating best practice using methods like TDD and bettering the quality of code.

Comments and Discussions

 
-- There are no messages in this forum --