Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/301.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/entity-framework/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 一对一/零关系问题实体框架_C#_Entity Framework - Fatal编程技术网

C# 一对一/零关系问题实体框架

C# 一对一/零关系问题实体框架,c#,entity-framework,C#,Entity Framework,出于复杂的历史原因,我有两个表格: 雇员 [Key] public int employee_ID { get; set; } public Nullable<int> employeeStatus_ID { get; set; } public string employeeFirstName { get; set; } public string employeeSurname { get; set; } ... 用户必须具有员工记录。员工记

出于复杂的历史原因,我有两个表格:

雇员

   [Key]
   public int employee_ID { get; set; }
   public Nullable<int> employeeStatus_ID { get; set; }
   public string employeeFirstName { get; set; }
   public string employeeSurname { get; set; }
   ...
用户必须具有员工记录。员工记录可能还没有用户记录

在我的数据上下文中,我有这样一个集合

   modelBuilder.Entity<User>().HasRequired(p => p.Employee)
                .WithOptional(x=>x.User);
它保存OK,并创建一个新用户。 不幸的是,我发现我的员工的新副本也是用新员工id创建的

我怎样才能阻止这一切?
使用Entity Framework 6.01

为什么Entity Framework会将现有对象重新插入我的数据库?msdn.microsoft.com/en-us/magazine/dn166926.aspxI遵循本文,并使用attach方法Context.Employees.Attachemployee;这解决了问题。谢谢Colin@Colin你最好把它作为答案贴出来,这样就更容易找到了
   modelBuilder.Entity<User>().HasRequired(p => p.Employee)
                .WithOptional(x=>x.User);
   employee = GetMyEmployee(employeeID);

      User NewUser = new User
                {
                    UserId = Guid.NewGuid(),
                    Username = userName,
                    ...
                    Employee = employee
                };

                Context.Users.Add(NewUser);
                Context.SaveChanges();