1
我有兩個名爲Activity和ActivityType的表。它們之間存在一對多的關係,ActivityType作爲父類,Activity作爲子類。InsertAllOnSubmit(LINQ to SQL)在相關表中生成重複條目
當我嘗試在Activity表中存儲新創建的實體並將其與已存在的ActivityType實體關聯時,我最終會得到這些預先存在的ActivityType實體的重複條目。
這怎麼可以避免?
這是我如何創建加關係新的活動實體預先存在的ActivityType實體:
var activities = (Session["Activities"] as List<D.Activity>);
if(activities == null)
activities = new List<D.Activity>();
using (var dbContext = new D.DataClassesDataContext())
{
var activityType = (from x in dbContext.ActivityTypes
where x.ClientID == this.Client.ClientID && x.ActivityTypeID == model.ActivityTypeID
select x).SingleOrDefault();
var activity = new D.Activity()
{
ActivityType = activityType,
ActivityTypeID = activityType.ActivityTypeID,
ClientID = this.Client.ClientID,
Description = model.ActivityDescription,
PerformedByEmployeeID = this.User.UserId,
PerformedDate = model.WorkDay,
ProjectID = model.EntityID,
StartTime = model.ActivityStartTime,
StopTime = model.ActivityStopTime
};
activities.Add(activity);
Session["Activities"] = activities;
}
這是我如何保存活動的實體:
using (var dbContext = new D.DataClassesDataContext())
{
var activities = (Session["Activities"] as List<D.Activity>);
dbContext.Activities.InsertAllOnSubmit(activities);
dbContext.SubmitChanges();
return View();
}
正確讀取您的問題後的更正:當您將列表寫入會話並因此重複時,加載的ActivityTypes被複制。 EF將它們視爲新實體,然後插入新記錄。 – drw85