EF - One-to-Many Relationships (Fully Defined Relationship)

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()
	{
		using (var context = new BookStore())
		{	
			Author author = new Author()
		    {
		        Name = "Mark",
		        Books = new List<Book>
				{
					new Book(){Title = "MyBook 1"},
					new Book(){Title = "MyBook 2"},
				}
		    };
			
		    context.Authors.Add(author);

		    context.SaveChanges();
			
			var authorData = context.Authors.ToList();
			var books = context.Books.ToList();
			FiddleHelper.WriteTable(authorData);
			FiddleHelper.WriteTable(books);
		}
	}
	
	public class BookStore : DbContext
    {
        public BookStore() : base(FiddleHelper.GetConnectionStringSqlServer())
        {
            
        }
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
        }

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

    public class Author
    {
        public int AuthorId { get; set; }
        public string Name { get; set; }
		public virtual ICollection<Book> Books { get; set; }
    }
	
	public class Book
    {
        public int BookId { get; set; }
        public string Title { get; set; }
		public int AuthorId { get; set; }
		public Author Author { get; set; }
    }
}
;