Guest User

EF Many-to-Many Self-Reference

a guest
Dec 16th, 2015
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.01 KB | None | 0 0
  1. //Item.cs
  2.     public class Item
  3.     {
  4.         public Item()
  5.         {
  6.             Composites = new HashSet<Item>();
  7.             Components = new HashSet<Item>();
  8.         }
  9.    
  10.         public int ItemId { get; set; }
  11.  
  12.         public string Name { get; set; }
  13.  
  14.         public int Cost { get; set; }
  15.  
  16.         public virtual ICollection<Item> Composites { get; set; }
  17.  
  18.         public virtual ICollection<Item> Components { get; set; }
  19.  
  20.     }
  21.  
  22. //MyContext.cs
  23.     public class MyContext : DbContext
  24.     {
  25.         public MyContext()
  26.             :base("DbConnection")
  27.         { }
  28.  
  29.         public DbSet<Item> Items { get; set; }
  30.  
  31.         protected override void OnModelCreating(DbModelBuilder modelBuilder)
  32.         {
  33.             modelBuilder.Entity<Item>()
  34.                 .HasMany(x => x.Composites)
  35.                 .WithMany(x => x.Components);
  36.         }
  37.     }
  38.  
  39. //MainWindow.xaml.cs
  40.     public partial class MainWindow : Window
  41.     {
  42.         public MainWindow()
  43.         {
  44.             InitializeComponent();
  45.  
  46.             AppDomain.CurrentDomain.SetData("DataDirectory", AppDomain.CurrentDomain.BaseDirectory);
  47.         }
  48.  
  49.         private void Window_Loaded(object sender, RoutedEventArgs e)
  50.         {
  51.             Database.SetInitializer<MyContext>(new CreateDatabaseIfNotExists<MyContext>());
  52.  
  53.             using (MyContext context = new MyContext())
  54.             {
  55.                 Item i1 = new Item() { Name = "Motherboard", Cost = 500 };
  56.                 Item i2 = new Item() { Name = "Network Adapter", Cost = 150 };
  57.                 Item i3 = new Item() { Name = "System Unit", Cost = 250 };
  58.  
  59.                 context.Items.Add(i1);
  60.                 context.Items.Add(i2);
  61.                 context.Items.Add(i3);
  62.  
  63.                 context.SaveChanges();
  64.                
  65.                 i3.Components.Add(i1);
  66.                 i3.Components.Add(i2);
  67.                 i1.Composites.Add(i3);
  68.                 i2.Composites.Add(i3);
  69.  
  70.                 context.SaveChanges();
  71.             }
  72.         }
  73.     }
Advertisement
Add Comment
Please, Sign In to add comment