Skip to content

Instantly share code, notes, and snippets.

@RhysC
Created October 16, 2012 04:12
Show Gist options
  • Save RhysC/3897197 to your computer and use it in GitHub Desktop.
Save RhysC/3897197 to your computer and use it in GitHub Desktop.
Most Simple Relational EF sample
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