Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //Item.cs
- public class Item
- {
- public Item()
- {
- Composites = new HashSet<ItemItem>();
- Components = new HashSet<ItemItem>();
- }
- public int ItemId { get; set; }
- public string Name { get; set; }
- public int Cost { get; set; }
- public virtual ICollection<ItemItem> Composites { get; set; }
- public virtual ICollection<ItemItem> Components { get; set; }
- public void AddComponent(MyContext context, Item item, [Range(1, Int32.MaxValue)] int quantity = 1)
- {
- var itemRelation = Components.FirstOrDefault(c => c.Composite == this);
- if (itemRelation == null)
- {
- itemRelation = new ItemItem() { Composite = this, Component = item, Quantity = quantity };
- this.Components.Add(itemRelation);
- item.Composites.Add(itemRelation);
- }
- else
- {
- itemRelation.Quantity += quantity;
- }
- }
- public void AddComposite(MyContext context, Item item, [Range(1, Int32.MaxValue)] int quantity = 1)
- {
- var itemRelation = Composites.FirstOrDefault(c => c.Component == this);
- if (itemRelation == null)
- {
- itemRelation = new ItemItem() { Component = this, Composite = item, Quantity = quantity };
- this.Composites.Add(itemRelation);
- item.Components.Add(itemRelation);
- }
- else
- {
- itemRelation.Quantity += quantity;
- }
- }
- }
- //ItemItem.cs
- public class ItemItem
- {
- public ItemItem()
- {
- }
- [Key]
- public int RelationId { get; set; }
- public int Quantity { get; set; }
- public virtual Item Composite { get; set; }
- public virtual Item Component { get; set; }
- }
- //MyContext.cs
- public class MyContext : DbContext
- {
- public MyContext()
- :base("DbConnection")
- { }
- public DbSet<Item> Items { get; set; }
- public DbSet<ItemItem> ItemItems { get; set; }
- }
- //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 = 0 };
- context.Items.Add(i1);
- context.Items.Add(i2);
- context.Items.Add(i3);
- context.SaveChanges();
- i3.AddComponent(context, i1);
- i3.AddComponent(context, i2);
- context.SaveChanges();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment