Created
October 16, 2012 04:12
-
-
Save RhysC/3897197 to your computer and use it in GitHub Desktop.
Most Simple Relational EF sample
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Data.Entity; | |
namespace EFConsoleApplication.Basic | |
{ | |
public class Parent | |
{ | |
public Parent() | |
{ | |
Children = new HashSet<Child>(); | |
} | |
public int ParentId { get; set; } | |
public string Name { get; set; } | |
public ICollection<Child> Children { get; set; } | |
} | |
public class Child | |
{ | |
public int ChildId { get; set; } | |
public string Name { get; set; } | |
} | |
public class SampleContext : DbContext | |
{ | |
public DbSet<Parent> Parents { get; set; } | |
} | |
public class SampleRunner | |
{ | |
//Entry point of app | |
public static void Run() | |
{ | |
using (var context = new SampleContext()) | |
{ | |
context.Database.Delete(); | |
context.Database.Create(); | |
} | |
var parent = new Parent { Name = "barry" }; | |
parent.Children.Add(new Child { Name = "Fred" }); | |
using (var context = new SampleContext()) | |
{ | |
context.Parents.Add(parent); | |
context.SaveChanges(); | |
} | |
using (var context = new SampleContext()) | |
{ | |
foreach (var p in context.Parents.Include(p => p.Children)) | |
{ | |
Console.WriteLine("Parent name: {0}, id :{1}", p.Name, p.ParentId); | |
Console.WriteLine("Children:"); | |
foreach (var c in p.Children) | |
{ | |
Console.WriteLine("\tname: {0}, id: {1}", c.Name, c.ChildId); | |
} | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment