因此,我正在開發一個應用程序,它將從一個數據庫中選擇數據,並根據Authoring數據庫中的「發佈」表中包含的信息更新相同的數據庫。我需要得到一個沒有連接到'創作'上下文的單個對象,所以我可以將它添加到我的'Delivery'上下文中。創建一個未連接的實體框架DbContext實體
目前我使用
object authoringRecordVersion = PublishingFactory.AuthoringContext.Set(recordType.Entity.GetType()).Find(record.RecordId);
object deliveryRecordVersion = PublishingFactory.DeliveryContext.Set(recordType.Entity.GetType()).Find(record.RecordId));
返回我的記錄。然後,如果'deliveryRecordVersion'爲空,我需要在'PublishingFactory.DeliveryContext'中插入'authoringRecordVersion'。但是,該對象已經連接到'PublishingFactory.AuthoringContext',因此它不會允許在'PublishingFactory.DeliveryContext'上調用Add()方法。
我有機會獲得PublishingFactory.AuthoringContext.Set(recordType.Entity.GetType()).AsNoTracking()
,但有沒有辦法讓在我從這裏需要的特定記錄。 有什麼建議嗎?
更新:
我相信我找到了解決方案。它第一次沒有工作,因爲我在設置時引用了錯誤的對象.State = EntityState.Detached; 這裏是完整的修正方法,預計
private void PushToDelivery(IEnumerable<Mkl.WebTeam.UWManual.Model.Publication> recordsToPublish)
{
string recordEntity = string.Empty;
DbEntityEntry recordType = null;
// Loop through recordsToPublish and see if the record exists in Delivery. If so then 'Update' the record
// else 'Add' the record.
foreach (var record in recordsToPublish)
{
if (recordEntity != record.Entity)
{
recordType = PublishingFactory.DeliveryContext.Entry(ObjectExt.GetEntityOfType(record.Entity));
}
if (recordType == null)
{
continue;
////throw new NullReferenceException(
//// string.Format("Couldn't identify the object type stored in record.Entity : {0}", record.Entity));
}
// get the record from the Authoring context from the appropriate type table
object authoringRecordVersion = PublishingFactory.AuthoringContext.Set(recordType.Entity.GetType()).Find(record.RecordId);
// get the record from the Delivery context from the appropriate type table
object deliveryRecordVersion = PublishingFactory.DeliveryContext.Set(recordType.Entity.GetType()).Find(record.RecordId);
// somthing happened and no records were found meeting the Id and Type from the Publication table in the
// authoring table
if (authoringRecordVersion == null)
{
continue;
}
if (deliveryRecordVersion != null)
{
// update record
PublishingFactory.DeliveryContext.Entry(deliveryRecordVersion).CurrentValues.SetValues(authoringRecordVersion);
PublishingFactory.DeliveryContext.Entry(deliveryRecordVersion).State = EntityState.Modified;
PublishingFactory.DeliveryContext.SaveChanges();
}
else
{
// insert new record
PublishingFactory.AuthoringContext.Entry(authoringRecordVersion).State = EntityState.Detached;
PublishingFactory.DeliveryContext.Entry(authoringRecordVersion).State = EntityState.Added;
PublishingFactory.DeliveryContext.SaveChanges();
}
recordEntity = record.Entity;
}
}
爲什麼「沒辦法」? '.Single(a => a.ID == record.RecordId);'? – 2013-04-03 21:00:11
1st因爲Single()不是after.AsNoTracking選項。 2nd因爲a.Id.由於objecttype「recordType.Entity.GetType()」類型在設計時不可用,所以不可用。 – Tim 2013-04-03 21:59:14