Created
March 2, 2016 03:29
-
-
Save shawnweisfeld/76df5574f99b7d1c3d08 to your computer and use it in GitHub Desktop.
EF Unary Relationship with Child Collection and Parent Object
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.ComponentModel.DataAnnotations; | |
using System.ComponentModel.DataAnnotations.Schema; | |
using System.Data.Entity; | |
using System.Linq; | |
using System.Text; | |
using System.Threading.Tasks; | |
namespace EFUnary | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
using (var ctx = new AppContext()) | |
{ | |
var page = new Page() | |
{ | |
Name = "blah", | |
SubPages = new List<Page> | |
{ | |
new Page { Name = "Child1" }, | |
new Page { Name = "Child2" }, | |
new Page { Name = "Child3" }, | |
} | |
}; | |
ctx.Pages.Add(page); | |
ctx.SaveChanges(); | |
var child = ctx.Pages.FirstOrDefault(x => x.Name == "Child1"); | |
Console.WriteLine(child.ParentPage.Name); | |
Console.ReadKey(); | |
} | |
} | |
} | |
public class AppContext : DbContext | |
{ | |
public AppContext() | |
: base (@"Server=.;Database=UnaryTest;Trusted_Connection=True;") | |
{ | |
} | |
public DbSet<Page> Pages { get; set; } | |
} | |
public class Page | |
{ | |
public int PageID { get; set; } | |
public string Name { get; set; } | |
public Page ParentPage { get; set; } | |
[InverseProperty("ParentPage")] | |
public virtual ICollection<Page> SubPages { get; set; } | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment