EF代码第一个问题。它创建新对象

时间:2018-09-26 14:29:19

标签: c# entity-framework entity-framework-6 ef-code-first ef-migrations

我是Entity Framework Code First的初学者。所以我在处理迁移时遇到了麻烦。所以这是一个问题:
我有以下型号:

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

DefectEntry具有:

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

所有其他模型都包含:

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

当我尝试为每个订单(订单和用户已知的)添加缺陷时,EF正在创建一个新订单,并且用户对象具有另一个ID(因为每个用户的ID是唯一的,并被视为Primary_key)。

 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());
            }
        }
    }

当我按下一个addButton时,我有这些重复项: User table look Defects table look Order table look Defect Entry table look

1 个答案:

答案 0 :(得分:0)

之所以这样做,是因为您的用户和订单实体与EF上下文断开了连接。在DefectEntry对象中使用它们之前,必须将它们重新附加到上下文。因此,您必须在using (MyBridgeContext context=new MyBridgeContext()) {方法内的addButton_Click语句之后立即执行以下操作:

context.Users.Attach(user);
context.Orders.Attach(order);