2013-05-08 31 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