2013-05-08 64 views
1

我有一個名爲Tour的表和另一個表名TourPlan。 這些表格如下相關;如何更新實體框架中的相關表?

Tour       TourPlan 
Id (PK,int,not null)   Id (PK, int, not null) 
Title (nvarchar(100), null)  Title (nvarchar(100), null) 
           TourId (FK, int, not null) 

問題是用現有值更新TourPlan表。

這是我更新的代碼;

Tour tour = TourController.GetTourById(Int32.Parse("13")); 
tour.TourPlan.Clear(); 
foreach (ListItem item in lbPlans.Items) 
    { 
    tour.TourPlan.Add(new TourPlan() { Title = item.Text }); 
    } 

這是我的更新方法;

public static int UpdateTour(Tour tour) 
{ 
    using (var context = new aisatourismEntities()) 
    { 
     Tour tUpd = context.Tour.FirstOrDefault(t => t.Id == tour.Id); 
      if (tUpd != null) 
      { 
       tUpd.Title = tour.Title; 
       tUpd.TourPlan = tour.TourPlan; 
      } 
      return context.SaveChanges(); 
    } 
} 

但它沒有更新,它插入計劃兩次。 我該如何解決這個問題?

回答

2

您將需要更新,而不是覆蓋實例TourPlan的數據:

public static int UpdateTour(Tour tour) 
{ 
    using (var context = new aisatourismEntities()) 
    { 
     Tour tUpd = context.Tour.FirstOrDefault(t => t.Id == tour.Id); 
      if (tUpd != null) 
      { 
       tUpd.Title = tour.Title; 
       tUpd.TourPlan.Id= tour.TourPlan.Id; 
       tUpd.TourPlan.TourId= tour.TourPlan.TourId; 
       tUpd.TourPlan.Title = tour.TourPlan.Title; 
      } 
      return context.SaveChanges(); 
    } 
} 

當然,這假設你已經有TourPlan的附加實例。如果不是,則需要將其附加到DbContext。

+0

Tour有多個TourPlan,所以兩個表之間有1對n的關係。 – 2013-05-08 09:21:34

+0

所以Tour.TourPlan是一個集合?在這種情況下,您應該遍歷集合並複製這些值。 – Kenneth 2013-05-08 09:39:53

+0

是的。這是收集。但是,如果用戶刪除了一個計劃並在更新中添加了另一個計劃,那麼這將如何實現? – 2013-05-08 09:51:39

1

這是你更新TourPlan應該像方法如何:

public static void UpdateTour(Tour tour, TourPlan tourPlan) 
    { 
     using (var context = new aisatourismEntities()) 
     { 
      context.Tours.Attach(tour); 

      context.Entity(tourPlan).Property(plan => plan.Title).IsModified = true; 

      context.SaveChanges(); 
     } 
    } 

方法的第二個參數必須是已經「準備」 TourPlan