2013-10-20 86 views
0

我遇到了這個特定方法中的問題。我第一次保存它通過在AppointmentEvent中創建單個記錄並更改Appointment中的已驗證變量,但它會再次創建用戶記錄。實體框架不斷創建多個記錄

private void CreateAppointment(Employee user) 
     { 
      try 
      { 
       using (var db = new CosmeticContext()) 
       { 
        Appointment appointment = db.Appointment.FirstOrDefault(o => o.name == phoneNumber.name && o.surname == phoneNumber.surname && o.verified == false); 
        appointment.verified = true; 
        PhoneNumber ph = db.PhoneNumber.FirstOrDefault(o => o.name == phoneNumber.name && o.surname == phoneNumber.surname); 
        db.PhoneNumber.Remove(ph); 
        db.AppointmentEvent.Add(new AppointmentEvent 
        { 
         date = DateTime.Now, 
         Employees = user, 
         Appointments = appointment, 
         EventComment = EventComment.Save 
        }); 
        db.SaveChanges(); 
       } 
      } 
      catch (System.Data.Entity.Validation.DbEntityValidationException e) 
      { 
       DbScript.ShowEntityErrors(e); 
      } 
     } 

當我運行它第二次它重複用戶,約會事件和約會記錄與以前的值。當我通過調試器時,我看到db.AppointmentEvent.Local有0條記錄,但在第二次添加方法後,在db.AppointmentEvent.Local中創建了2條記錄。我不明白如何一個添加方法可以添加2條記錄。谷歌並沒有爲我提供正確的案例,但不應該使用正確的方式處理一切?

這裏是包含對象的一些附加類,這裏使用:

public class Employee 
{ 
    [Key] 
    public int employeeId { get; set; } 
    [Required, MaxLength(25), MinLength(4)] 
    public string userName { get; set; } 
    [Required, MaxLength(25), MinLength(4)] 
    public string firstName { get; set; } 
    [Required, MaxLength(25), MinLength(4)] 
    public string lastName { get; set; } 
    [Required, MaxLength(100), MinLength(20)] 
    public string password { get; set; } 
    [Required] 
    public EmployeeType EmployeeType { get; set; } 
    public virtual List<PhoneNumber> PhoneNumbers { get; set; } 
    public virtual List<AppointmentEvent> AppointmentEvents { get; set; } 
} 

public class AppointmentEvent 
{ 
    public int appointmentEventId { get; set; } 
    [Required] 
    public DateTime date { get; set; } 
    [Required] 
    public virtual Employee Employees { get; set; } 
    [Required] 
    public virtual Appointment Appointments { get; set; } 
    [Required] 
    public EventComment EventComment { get; set; } 
} 

public class Appointment 
{ 
    [Key] 
    public int appointmentId { get; set; } 
    [Required, MaxLength(20)] 
    public string name { get; set; } 
    [Required, MaxLength(30)] 
    public string surname { get; set; } 
    [Required, MaxLength(20), Phone] 
    public string phone { get; set; } 
    [Required] 
    public DateTime date { get; set; } 
    [Required] 
    public ServiceType ServiceType { get; set; } 
    [Required] 
    public bool verified { get; set; } 
    public virtual List<AppointmentEvent> AppointmentEvents { get; set; } 
} 

編輯:忘了告訴大家,我創建一個Windows窗體應用程序和更多的代碼,這表明用戶部分: 這即形式nr2.:(in我有記錄的問題)

public partial class CallCenter : Form 
    { 
     Employee employee; 
     static ListTime listTime = new ListTime(); 
     Button pushedButton = new Button(); 

     public CallCenter(Employee loginEmployee) 
     { 

      employee = loginEmployee; 

      InitializeComponent(); 
      tableLayoutPanel2.CellPaint += tableLayoutPanel1_CellPaint; 
      GeneratedServiceTypeComboBox.DataSource = Enum.GetValues(typeof(ServiceType)); 
      textBox1.Text = DateTime.Now.AddDays(1).Date.ToString("dd.MM.yyyy"); 
      textBox2.Text = DateTime.Now.AddDays(2).Date.ToString("dd.MM.yyyy"); 
      RefreshAppointmentAvailabilityTable(); 
     } 

    private void SaveButton_Click(object sender, EventArgs e) 
     { 
      try 
      { 
       GenerateButton.Enabled = true; 
       SaveButton.Enabled = false; 
       this.NameBox.Text = string.Empty; 
       SurnameBox.Text = string.Empty; 
       PhoneBox.Text = string.Empty; 
       GeneratedNameBox.Text = string.Empty; 
       GeneratedSurnameBox.Text = string.Empty; 
       GeneratedPhoneBox.Text = string.Empty; 
       pushedButton.BackColor = Color.LightGreen; 
       ChangeAppointmentAvailabilityButtonsStatus(false); 
       CreateAppointment(employee); 
      } 
      catch (Exception f) 
      { MessageBox.Show(f.ToString()); } 

     } 
    ... 
    } 

這是Form1中:(登錄屏幕)

private void LoginButton_Click(object sender, EventArgs e) 
    { 
     using (var db = new CosmeticContext()) 
     { 
      bool verify = false; 
      Employee employee = db.Employee.FirstOrDefault(o => o.userName == UserNameBox.Text); 
      if (employee == null) 
       MessageBox.Show("Sads lietotajs nav atrasts datubaze", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Error); 
      else 
      { 
       verify = PasswordAlgorithm.DoesPasswordMatch(employee.password, PasswordBox.Text); 
       if (verify) 
        if (employee.EmployeeType == EmployeeType.Seller) 
        { 
         CallCenter form1 = new CallCenter(employee); 
         form1.Show(); 
         this.Hide(); 
        } 
      } 
     } 
    } 
+0

其中'用戶'定義在僱員=用戶,'塊?請告訴我們代碼! – sarwar026

+0

@ sarwar026添加了代碼。 –

+0

,因爲你是從數據庫中提取'user',我在代碼中看不到任何問題!等待看到一些優雅的答案! – sarwar026

回答

0

您的用戶是否被EntityFramework上下文跟蹤? 如果沒有跟蹤EF不知道更好,並會很樂意使關聯,但通過添加一個新的用戶,而不是將約會與現有的關聯。我懷疑這是在這裏發生了什麼:

ObjectContext.AddObjectObjectSet.AddObject: AddObject方法用於添加數據庫中不存在的新創建的對象。該實體將獲得一個自動生成的臨時EntityKey,並將其EntityState設置爲已添加。當調用SaveChanges時,EF將清楚該實體需要插入到數據庫中。

ObjectContext.AttachObjectSet.Attach: 另一方面,Attach用於數據庫中已存在的實體。將結果添加到未更改的EntityState中,而不是將EntityState設置爲已添加,這意味着它自從附加到上下文後沒有更改。假定您附加的對象存在於數據庫中。如果在對象被修改後修改對象,當調用SaveChanges時,EntityKey的值將用於通過在db表中查找匹配的ID來更新(或刪除)適當的行。

+0

感謝您的解決方案引導我回答。 我把 db.Employee.Attach(user); 在即時保存和現在它正常工作的地方。 –