0
我在我的實體內部的一個方法中創建一個上下文來檢查某些東西,但我沒有跟蹤任何東西,但是當我嘗試保存在調用代碼上下文中時,它會引發異常。實體附加到上下文並且無法刪除它
這是主要的背景下調用代碼,我要保存:
var espToProcess = db.RootDomainEmailSeriesProgresses;
foreach (var esp in espToProcess)
{
bool carryOn = esp.MoveNext();
db.SaveChanges(); //Exception
if (!carryOn) continue;
//--> rest of my code
}
這是RootDomainEmailSeriesProgress
類中的方法。
public bool MoveNext()
{
if (this.CompletedTargets == null) this.CompletedTargets = new List<EmailAddress>();
if (this.CurrentTarget != null)
{
this.CompletedTargets.Add(this.CurrentTarget);
this.CurrentTarget = null;
}
this.CurrentProgress = "";
if (this.RootDomain.ContactFilter != RootDomain.ContactFilterType.None)
{
this.Status = EmailSeriesStatus.Aborted;
return false;
}
var allTargets = RootDomainEmailManager.SortDomainsEmailsByDesirability(this.RootDomain.ID);
var toDo = allTargets.Except(this.CompletedTargets);
if (toDo.Count() < 1)
{
this.Status = EmailSeriesStatus.Completed;
return false;
}
List<string> targetEmailList = allTargets.Select(e => e.Email).ToList();
List<EmailFilter> emailFilters = this.GetFilters(allTargets);
if (emailFilters.Any(x => x.Filter == EmailFilterType.Unsubscribe || x.Filter == EmailFilterType.Responded || x.Filter == EmailFilterType.ManualContactOnly))
{
this.Status = EmailSeriesStatus.Aborted;
if (this.RootDomain.ContactFilter == 0) this.RootDomain.ContactFilter = RootDomain.ContactFilterType.HasAssociatedEmailFilter;
return false;
}
this.CurrentTarget = toDo.First();
return true;
}
private List<EmailFilter> GetFilters(List<EmailAddress> allTargets)
{
using (var db = new PlaceDBContext())
{
db.Configuration.AutoDetectChangesEnabled = false;
db.Configuration.LazyLoadingEnabled = false;
var targetEmailList = allTargets.Select(e => e.Email).ToList();
return db.EmailFilters.AsNoTracking().Where(x => targetEmailList.Contains(x.Email)).ToList();
}
}
它拋出該異常:
兩個對象之間的關係不能被限定,因爲它們連接到不同的ObjectContext對象。
我看不出爲什麼esp
被連接到另一個上下文。我只是簡單地需要這個背景,我如何將它關閉以免它導致我遇到問題?
我得到同樣的錯誤 – Guerrilla