我想增加现有实体的参考成员。
我需要为upsert编写特定的代码吗?
含义:我必须检查是在处理现有参考成员还是新参考成员。
还有其他简单的方法吗?
当您只做时会发生什么Save?
Save
public void SaveCofiguration(MamConfiguration_V1Ui itemUi) { var itemEf = mMamConfiguration_V1UiToEfConvertor.ConvertToNewEf(itemUi); using (var maMDBEntities = new MaMDBEntities()) { IDal<MamConfiguration_V1> mamConfigurationDal = mDalFactory.GetDal<MamConfiguration_V1>(maMDBEntities); mamConfigurationDal.Save(itemEf); } } public MamConfiguration_V1 GetById(object id) { id.ThrowIfNull("id"); int configurationId = Convert.ToInt32(id); var result = mMaMDBEntities.MamConfiguration_V1.SingleOrDefault(item => item.ConfigurationId == configurationId); return result; } public MamConfiguration_V1 Save(MamConfiguration_V1 item) { item.ThrowIfNull("item"); var itemFromDB = GetById(item.ConfigurationId); if (itemFromDB != null) { UpdateEfItem(itemFromDB, item); // if (mMaMDBEntities.ObjectStateManager.GetObjectStateEntry(itemFromDB).State == EntityState.Detached) // { // mMaMDBEntities.MamConfiguration_V1.AddObject(itemFromDB); // } // Attached object tracks modifications automatically mMaMDBEntities.SaveChanges(); return item; } private void UpdateEfItem(MamConfiguration_V1 itemFromDb, MamConfiguration_V1 itemFromUi) { itemFromDb.UpdatedDate = DateTime.Now; itemFromDb.Description = itemFromUi.Description; itemFromDb.StatusId = itemFromUi.StatusId; itemFromDb.Name = itemFromUi.Name; itemFromDb.NumericTraffic = itemFromUi.NumericTraffic; itemFromDb.PercentageTraffic = itemFromUi.PercentageTraffic; itemFromDb.Type = itemFromUi.NumericTraffic; foreach (var item in itemFromDb.MamConfigurationToBrowser_V1.ToList()) { if (itemFromUi.MamConfigurationToBrowser_V1.All(b => b.BrowserVersionId != item.BrowserVersionId)) { mMaMDBEntities.MamConfigurationToBrowser_V1.DeleteObject(item); } } for (int i = 0; i < itemFromUi.MamConfigurationToBrowser_V1.Count; i++) { var element = itemFromUi.MamConfigurationToBrowser_V1.ElementAt(i); var item = itemFromDb.MamConfigurationToBrowser_V1.SingleOrDefault(b => b.BrowserVersionId == element.BrowserVersionId); if (item != null) { // copy properties from element to item } else { element.Browser = mMaMDBEntities.Browsers.Single(browserItem => browserItem.BrowserID == element.BrowserID); //element.MamConfiguration_V1 = itemFromDb; //have also tried: element.MamConfiguration_V1 = null; //element.MamConfiguration_V1Reference = null; itemFromDb.MamConfigurationToBrowser_V1.Add(element); } } }
但我会期望Save(itemUi)并SaveChanges()能正常工作。不?
Save(itemUi)
SaveChanges()
public void InsertOrUpdate(DbContext context, UEntity entity) { context.Entry(entity).State = entity.Id == 0 ? EntityState.Added : EntityState.Modified; context.SaveChanges(); }
http://forums.asp.net/t/1889944.aspx/1