EF Code first problem. It creates the new objects

c# ef-code-first ef-migrations entity-framework entity-framework-6

Question

Entity Framework Code First is a new concept for me. Consequently, I'm having problems using migrations. Thus, this is a problem:
I have the models below:

Defect - table of defects(general)
User - table of users
Order - table or orders
DefectEntry - defects per order(entered by a user).

DefectEntry includes:

public virtual Defect defect { get; set; }
public virtual User user { get; set; }
public virtual Order order { get; set; }

All additional models include:

public virtual ICollection<DefectEntry> Entries { get; set; }

Since each user's ID is unique and is used as the primary key, when I attempt to record a fault for each order (order and user known), the EF creates new order and user objects with entirely different IDs.

 private Order order;
 private User user;

public AddDefect(ref Order order, ref User user) //this is a name of UserControl
    {
        InitializeComponent();
        this.order = order;
        this.user = user;
        loadDefects();
    }

private void loadDefects()
    {
        using (MyBridgeContext context = new MyBridgeContext())
        {
            var defects = context.Defects;
            foreach (var obj in defects)
            {
                defectList.Items.Add(obj);
            }
        }
    }

private void addButton_Click(object sender, RoutedEventArgs e)
    {
        if (doubleCheck.IsChecked == true)
        {
            try
            {
                using (MyBridgeContext context = new MyBridgeContext())
                {
                    DefectEntry entry = new DefectEntry();

                    foreach (Defect def in defectList.Items)
                    {
                        if(defectList.SelectedItem == def)
                        {
                            entry.defect = def;
                        }
                    }

                    entry.user = user;
                    entry.order = order;
                    entry.dt = DateTime.Now;

                    context.Entries.Add(entry);
                    context.SaveChanges();


                    this.Content = new MainMonitoring(ref order, ref user);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
    }

I get duplicates like these when I press an addButton: User table lookTable flaws lookordering a tablePoor entry table appearance

1
0
9/26/2018 2:29:19 PM

Popular Answer

ZZZ_tmp
0
9/26/2018 3:10:47 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow