CSharp · Console
// @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 authors = context.Authors
.Select(author => new
{
Id = author.AuthorId,
FullName = author.FirstName + " " + author.LastName,
Books = author.Books
}).ToList();
foreach(var author in authors)
{
Console.WriteLine("Author Name: " + author.FullName);
Console.WriteLine("\tBook List:");
foreach (var book in author.Books)
{
Console.WriteLine("\t\t" + book.Title);
}
}
}
}
public static void InsertData()
{
using (var context = new BookStore())
{
var Authors = new List<Author>
{
new Author() {FirstName = "Mark", LastName = "Cuban"},
new Author() {FirstName = "Andy", LastName = "Holloway"},
new Author() {FirstName = "Johny", LastName = "bravo"}
};
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 FirstName { get; set; }
public string LastName { get; set; }
public virtual ICollection<Book> Books { get; set; }
}
}