Code First, Entity Framework 6, many-to-many table dependencies.
There are two classes (their reduced interfaces resulted):
public interface IEquipment { int Id { get; set; } string Name { get; set; } string Description { get; set; } List<Material> Materials { get; set; } } public interface IMaterial { int Id { get; set; } string Name { get; set; } string Description { get; set; } List<Equipment> Equipments { get; set; } } If you add new Materials to Equipments then everything works as it should. but when I try to add an already existing Material, side effects appear (it depends on those examples that I could google). Basically another pair of Equipment and a pair of Materials is created, sometimes nothing happens. Here is the latest code I used to add an existing Material to Equipment:
public void AddExistingMaterial() { using (EditorPostgresContext<Equipment> db = new EditorPostgresContext<Equipment>()) { if (SelectedMaterial != null) { var equipment = db.Objects.SingleOrDefault(a => a.Id == SelectedEquipment.Id); equipment.Materials.Add(SelectedMaterial); db.SaveChanges(); } } } The method is triggered when the user selects an existing Material in ListBox:
public Material SelectedMaterial { get { return GetValue<Material>(SelectedMaterialProperty); } set { SetValue(SelectedMaterialProperty, value); AddExistingMaterial(); } } public static readonly PropertyData SelectedMaterialProperty = RegisterProperty("SelectedMaterial", typeof(Material), null); Actually questions, if something I am doing wrong, please indicate where.
If the method is called in the wrong place, then how can you implement the right place in MVVM conditions, if you select from the list already present in the Materials database.
How can you add in the many-to-many conditions the amount of Materials for Equipment. For example, to create any equipment you need 10 materials. as I imagine, the best option would be to add to the intermediate table the third column where the number 10 is indicated. But how to do it in the above conditions if the table is created automatically by the framework?