private void SaveModelObject() { if (_dbModelObject == null) { GetDBModelObject(); } using (WebDbPoliticsModel context = new WebDbPoliticsModel()) { DbSet set = context.Set(EntityType); //var existing = set.Find(Id); var entry = context.Entry(_dbModelObject); set.Attach(_dbModelObject); entry.CurrentValues.SetValues(_modelObject); //entry.State = EntityState.Modified; var navigationProperties = (_modelObject as IModelObject).GetNavigationProperties(); foreach (var property in navigationProperties) { Type navigationType = property.PropertyType; DbSet navSet = context.Set(navigationType.GenericTypeArguments.First()); var navigationItemCollection = property.GetValue(_modelObject) as IEnumerable; foreach (var navigationItem in navigationItemCollection) { long id = navigationItem.GetId(); if (id > 0) { var existingNavigationItem = navSet.Find(id); context.Entry(existingNavigationItem).CurrentValues.SetValues(navigationItem); } else { navSet.Add(navigationItem); } } //navSet.Attach(navigationItem); } //context.UpdateGraph(_modelObject); // Add extension method for getting navigation properties of a modelobject // Then iterate them here and save any that are modified. //set.Add(_modelObject); //context.Entry(_modelObject).State = EntityState.Modified; var validationErrors = context.GetValidationErrors(); //existing = _modelObject; context.SaveChanges(); _dbModelObject = _modelObject; } }
private object LoadEntityFromDb() { using (WebDbPoliticsModel context = new WebDbPoliticsModel()) { context.Configuration.ProxyCreationEnabled = false; DbSet set = context.Set(EntityType); return(set.Find(Id)); } }
private void GetDBModelObject() { using (WebDbPoliticsModel context = new WebDbPoliticsModel()) { DbSet set = context.Set(EntityType); //var objectStateEntry = ((IObjectContextAdapter)this).ObjectContext.ObjectStateManager.GetObjectStateEntry(entry.Entity); //return objectStateEntry.EntityKey.EntityKeyValues[0].Value; _dbModelObject = set.Find(_modelObject.GetId()); } }
private object WriteEntityToDb(AddEntityRequest message) { Newtonsoft.Json.Linq.JObject jsonObject = message.ModelObject as Newtonsoft.Json.Linq.JObject; var entityAssembly = Assembly.GetAssembly(typeof(EntityFramework.WebDbPoliticsModel)); Type entityType = entityAssembly.GetTypes().FirstOrDefault(t => t.Name == message.EntityType); object modelObject = jsonObject.ToObject(entityType); var modelType = modelObject.GetType(); using (WebDbPoliticsModel db = new WebDbPoliticsModel()) { db.Configuration.ProxyCreationEnabled = false; DbSet set = db.Set(modelType); var resultObject = set.Add(modelObject); db.SaveChanges(); return(resultObject); } }