我有一个名为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 });
}这是我的update方法;
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();
}
}但是它没有更新,它插入了两次plan。我该如何解决这个问题呢?
发布于 2013-05-08 17:18:14
您需要更新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。
发布于 2015-04-23 17:39:59
下面是用于更新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。
https://stackoverflow.com/questions/16436785
复制相似问题