Skip to content

Instantly share code, notes, and snippets.

@paigecook
Created June 24, 2011 15:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save paigecook/1045067 to your computer and use it in GitHub Desktop.
Save paigecook/1045067 to your computer and use it in GitHub Desktop.
SO Question 6466936
using System;
using System.Collections.Generic;
using System.Data.Entity;
namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
CreateData();
GetData();
}
private static void GetData()
{
var context = new TestContext();
var theIssue = context.Issues.Find(1);
Console.WriteLine("Issue Id {0}", theIssue.ID);
Console.WriteLine("- Category {0}", theIssue.category.desc);
Console.WriteLine("- SubCategory {0}", theIssue.subCategory.desc);
}
private static void CreateData()
{
Console.WriteLine("Creating Data");
var context = new TestContext();
var parent = new Category()
{
desc = "Parent",
};
context.Categories.Add(parent);
context.SaveChanges();
var sub = new Category()
{
desc = "Sub",
parentId = parent.ID,
parentCategory = parent
};
context.Categories.Add(sub);
context.SaveChanges();
var issue = new Issue()
{
category = parent,
categoryID = parent.ID,
subCategory = sub,
subCategoryID = sub.ID,
};
context.Issues.Add(issue);
context.SaveChanges();
Console.WriteLine("Data Created");
}
}
public class Category
{
public int ID { get; set; }
public string desc { get; set; }
public int? parentId { get; set; }
public virtual Category parentCategory { get; set; }
public virtual ICollection<Issue> issues { get; set; }
}
public class Issue
{
public int ID { get; set; }
public int categoryID { get; set; }
public int subCategoryID { get; set; }
public virtual Category category { get; set; }
public virtual Category subCategory { get; set; }
}
public class TestContext : DbContext
{
public DbSet<Category> Categories { get; set; }
public DbSet<Issue> Issues { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Category>().HasOptional(c => c.parentCategory).WithMany().HasForeignKey(s => s.parentId);
modelBuilder.Entity<Issue>().HasRequired(i => i.category).WithMany().HasForeignKey(c => c.categoryID).WillCascadeOnDelete(false);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment