EF - Joining

CSharp · Console

/Program.cs

// @nuget: EntityFramework

using System;
using System.Data.Entity;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;

public class Program
{
	public static void Main()
	{
		InsertData();
		
		using (var context = new BookStore())
		{
            var data = context.Authors
				.Join(
					context.Books,
                    author => author.AuthorId,
                    book => book.Author.AuthorId,
                    (author, book) => new
                    {
                        BookId = book.BookId,
                        AuthorName = author.Name,
                        BookTitle = book.Title
                    }
                ).ToList();
			
			foreach(var book in data)
			{
				Console.WriteLine("Book Title: {0} \n\t Written by {1}", book.BookTitle, book.AuthorName);
			}
		}
		
	}
	
	public static void InsertData()
	{
		using (var context = new BookStore())
		{
			var Authors = new List<Author>
			{
				new Author() {Name = "Mark"},
				new Author() {Name = "Andy"},
				new Author() {Name = "Johny"}
			};
			
			var Books = new List<Book>
			{
				new Book() { Title = "Fundamentals of Computer Programming with C#", AuthorId = 1},
				new Book() { Title = "Java: A Beginner's Guide", AuthorId = 1},
				new Book() { Title = "SQL: The Ultimate Beginners Guide", AuthorId = 2},
				new Book() { Title = "Learn VB.NET", AuthorId = 3},
				new Book() { Title = "C# Fundamentals for Absolute Beginners", AuthorId = 3}
			};
			
		    context.Authors.AddRange(Authors);
			
			context.Books.AddRange(Books);
			
			context.SaveChanges();
			
		}
	}
	
	public class BookStore : DbContext
    {
        public BookStore() : base(FiddleHelper.GetConnectionStringSqlServer())
        {
        }

        public DbSet<Author> Authors { get; set; }
        public DbSet<Book> Books { get; set; }
    }

    public class Book
	{
    	public int BookId { get; set; }
	    public string Title { get; set; }
	    public int AuthorId { get; set; }
	    [ForeignKey("AuthorId")]
    	public Author Author { get; set; }
	}

    public class Author
	{
    	public int AuthorId { get; set; }
    	public string Name { get; set; }
	}
}
;