Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //Item.cs
- public class Item
- {
- public Item()
- {
- Composites = new HashSet<Item>();
- Components = new HashSet<Item>();
- }
- public int ItemId { get; set; }
- public string Name { get; set; }
- public int Cost { get; set; }
- public virtual ICollection<Item> Composites { get; set; }
- public virtual ICollection<Item> Components { get; set; }
- }
- //MyContext.cs
- public class MyContext : DbContext
- {
- public MyContext()
- :base("DbConnection")
- { }
- public DbSet<Item> Items { get; set; }
- protected override void OnModelCreating(DbModelBuilder modelBuilder)
- {
- modelBuilder.Entity<Item>()
- .HasMany(x => x.Composites)
- .WithMany(x => x.Components);
- }
- }
- //MainWindow.xaml.cs
- public partial class MainWindow : Window
- {
- public MainWindow()
- {
- InitializeComponent();
- AppDomain.CurrentDomain.SetData("DataDirectory", AppDomain.CurrentDomain.BaseDirectory);
- }
- private void Window_Loaded(object sender, RoutedEventArgs e)
- {
- Database.SetInitializer<MyContext>(new CreateDatabaseIfNotExists<MyContext>());
- using (MyContext context = new MyContext())
- {
- Item i1 = new Item() { Name = "Motherboard", Cost = 500 };
- Item i2 = new Item() { Name = "Network Adapter", Cost = 150 };
- Item i3 = new Item() { Name = "System Unit", Cost = 250 };
- context.Items.Add(i1);
- context.Items.Add(i2);
- context.Items.Add(i3);
- context.SaveChanges();
- i3.Components.Add(i1);
- i3.Components.Add(i2);
- i1.Composites.Add(i3);
- i2.Composites.Add(i3);
- context.SaveChanges();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment