public void Delete() { try { using (var cont = new healthychefEntities()) { System.Data.EntityKey key = cont.CreateEntityKey("hccCartDefaultMenuExPrefs", this); object originalItem = null; if (cont.TryGetObjectByKey(key, out originalItem)) { hccCartDefaultMenuExPref item = cont.hccCartDefaultMenuExPrefs .Where(a => a.MenuExPrefID == this.MenuExPrefID).SingleOrDefault(); if (item != null) { cont.hccCartDefaultMenuExPrefs.DeleteObject(item); cont.SaveChanges(); } } } } catch (Exception) { throw; } }
private RolodexEF.Ranks GetRank(int rankID) { using (var manager = ObjectContextManager <RolodexEntities> .GetManager(DataConnection.EFConnectionName, true)) { RolodexEF.Ranks rank; System.Data.EntityKey rankKey = new System.Data.EntityKey("RolodexEntities.Ranks", "RankId", rankID); System.Data.Objects.ObjectStateEntry entry; if (!manager.ObjectContext.ObjectStateManager.TryGetObjectStateEntry(rankKey, out entry)) { rank = new RolodexEF.Ranks(); rank.RankId = rankID; rank.EntityKey = rankKey; manager.ObjectContext.Attach(rank); } else { rank = entry.Entity as RolodexEF.Ranks; } return(rank); } }
//static healthychefEntities cont //{ // get { return healthychefEntities.Default; } //} public void Save() { try { using (var cont = new healthychefEntities()) { System.Data.EntityKey key = cont.CreateEntityKey("hccCartDefaultMenuExPrefs", this); object oldObj; if (cont.TryGetObjectByKey(key, out oldObj)) { cont.ApplyCurrentValues("hccCartDefaultMenuExPrefs", this); } else { cont.hccCartDefaultMenuExPrefs.AddObject(this); } cont.SaveChanges(); } } catch { throw; } }
//static healthychefEntities cont //{ // get { return healthychefEntities.Default; } //} public void Save() { try { using (var cont = new healthychefEntities()) { System.Data.EntityKey key = cont.CreateEntityKey("hccProgramDefaultMenus", this); object oldObj; if (cont.TryGetObjectByKey(key, out oldObj)) { cont.ApplyCurrentValues("hccProgramDefaultMenus", this); } else { cont.hccProgramDefaultMenus.AddObject(this); } cont.SaveChanges(); //cont.Refresh(System.Data.Objects.RefreshMode.StoreWins, this); } } catch { throw; } }
/// <summary> /// Gets the entity key of the specified entity type in the <see cref="DbContext" />. /// </summary> /// <param name="dbContext">The db context.</param> /// <param name="dbEntityEntry">Type of the entity.</param> /// <returns>The entity key.</returns> /// <exception cref="ArgumentNullException">The <paramref name="dbContext"/> is <c>null</c>.</exception> /// <exception cref="ArgumentNullException">The <paramref name="dbEntityEntry"/> is <c>null</c>.</exception> public static EntityKey GetEntityKey(this DbContext dbContext, DbEntityEntry dbEntityEntry) { Argument.IsNotNull("dbContext", dbContext); Argument.IsNotNull("dbEntityEntry", dbEntityEntry); var entityType = dbEntityEntry.GetEntityType(); var keySet = _entityKeyCache.GetFromCacheOrFetch(new Tuple <Type, Type>(dbContext.GetType(), entityType), () => { var entitySet = dbContext.GetEntitySet(entityType); return((from keyMember in entitySet.ElementType.KeyMembers select keyMember.Name).ToList()); }); var entitySetName = dbContext.GetFullEntitySetName(entityType); var currentValues = dbEntityEntry.CurrentValues; var keys = new List <EntityKeyMember>(); foreach (var keySetItem in keySet) { keys.Add(new EntityKeyMember { Key = keySetItem, Value = currentValues[keySetItem] }); } var entityKey = new EntityKey(entitySetName, keys.ToArray()); return(entityKey); }
public void Delete() { try { using (var cont = new healthychefEntities()) { System.Data.EntityKey key = cont.CreateEntityKey("hccProgramDefaultMenuExPrefs", this); object originalItem = null; if (cont.TryGetObjectByKey(key, out originalItem)) { List <hccProgramDefaultMenuExPref> items = cont.hccProgramDefaultMenuExPrefs .Where(a => a.DefaultMenuId == this.DefaultMenuId).ToList(); if (items.Count > 0) { foreach (var item in items) { cont.hccProgramDefaultMenuExPrefs.DeleteObject(item); cont.SaveChanges(); } } } } } catch (Exception) { throw; } }
public T GetByID(int id) { System.Data.EntityKey key = new System.Data.EntityKey(_db.DefaultContainerName + "." + typeof(T).Name, "ID", id); object obj = null; _db.TryGetObjectByKey(key, out obj); if (obj == null) { return(null); } _db.Detach(obj); return((T)obj); }
/// <summary> /// Recovery an object by their string primary key /// </summary> /// <param name="key">the string primary key</param> /// <returns>An TEntityObject</returns> public TEntityObject GetById(string key) { try { var set = this.Context.CreateObjectSet <TEntityObject>().EntitySet; var pk = set.ElementType.KeyMembers[0]; System.Data.EntityKey entityKey = new System.Data.EntityKey(set.EntityContainer.Name + "." + set.Name, pk.Name, key); return((TEntityObject)this.Context.GetObjectByKey(entityKey)); } catch { return(null); } }
//static healthychefEntities cont //{ // get { return healthychefEntities.Default; } //} public int Save() { try { using (var cont = new healthychefEntities()) { System.Data.EntityKey key = cont.CreateEntityKey("hccProductionCalendars", this); object oldObj; if (cont.TryGetObjectByKey(key, out oldObj)) { cont.ApplyCurrentValues("hccProductionCalendars", this); } else { cont.hccProductionCalendars.AddObject(this); } cont.SaveChanges(); return(this.CalendarID); } } catch (Exception ex) { if (ex.InnerException != null && ex.InnerException is SqlException) { try { if (ex.InnerException.Message.Contains("Cannot insert duplicate key row")) { return(GetBy(this.DeliveryDate).CalendarID); } else { throw; } } catch (Exception) { throw; } } else { throw ex; } } }
/// <summary> /// 修改实体审核状态 /// </summary> /// <param name="strEntityName">实体名</param> /// <param name="EntityKeyName">主键名</param> /// <param name="EntityKeyValue">主键值</param> /// <param name="CheckState">审核状态</param> public int UpdateCheckState(string strEntityName, string EntityKeyName, string EntityKeyValue, string CheckState) { int UpdateCont = 0; string qualifiedEntitySetName = ConfigurationManager.AppSettings["DBContextName"] + "."; Dictionary <object, object> Prameters = new Dictionary <object, object>(); Prameters.Add("CHECKSTATE", CheckState); try { System.Data.EntityKey entityKey = new System.Data.EntityKey(qualifiedEntitySetName + strEntityName, EntityKeyName, EntityKeyValue); object obj = GetObjectByEntityKey(entityKey); if (obj != null) { Type a = obj.GetType(); PropertyInfo[] infos = a.GetProperties(); foreach (PropertyInfo prop in infos) { if (Prameters.ContainsKey(prop.Name)) { prop.SetValue(obj, Prameters[prop.Name], null); } } UpdateCont = base.Update(obj); if (UpdateCont > 0) { Tracer.Debug("手机版修改表单状态,表单名:" + strEntityName + "单据号:" + EntityKeyValue + System.DateTime.Now.ToString()); BLLCommonServices.Utility.SubmitMyRecord <TEntity>(obj); } else { Tracer.Debug("手机版修改表单状态没有修改:" + strEntityName + "单据号:" + EntityKeyValue + System.DateTime.Now.ToString()); } } else { Tracer.Debug("手机版修改表单不存在:" + strEntityName + "单据号:" + EntityKeyValue + System.DateTime.Now.ToString()); } } catch (Exception ex) { //Tracer.Debug("手机版修改表单状态,表单名:" + strEntityName + "单据号:" + EntityKeyValue +System.DateTime.Now.ToString() + " " + ex.ToString()); Tracer.Debug("手机版修改表单状态出现错误:" + strEntityName + "单据号:" + EntityKeyValue + System.DateTime.Now.ToString() + "手机版修改表单状态出现错误: " + EntityKeyValue + "错误原因:" + ex.ToString()); //throw (ex); } return(UpdateCont); }
/// <summary> /// Gets the entity key of the specified entity type in the <see cref="DbContext" />. /// </summary> /// <param name="dbContext">The db context.</param> /// <param name="entityType">Type of the entity.</param> /// <param name="keyValue">The key value.</param> /// <returns>The entity key.</returns> /// <exception cref="ArgumentNullException">The <paramref name="dbContext"/> is <c>null</c>.</exception> /// <exception cref="ArgumentNullException">The <paramref name="entityType"/> is <c>null</c>.</exception> /// <exception cref="ArgumentNullException">The <paramref name="keyValue"/> is <c>null</c>.</exception> public static EntityKey GetEntityKey(this DbContext dbContext, Type entityType, object keyValue) { Argument.IsNotNull("dbContext", dbContext); Argument.IsNotNull("entityType", entityType); Argument.IsNotNull("keyValue", keyValue); var keyPropertyName = _entityKeyPropertyNameCache.GetFromCacheOrFetch(new Tuple <Type, Type>(dbContext.GetType(), entityType), () => { var entitySet = GetEntitySet(dbContext, entityType); return(entitySet.ElementType.KeyMembers[0].ToString()); }); var entitySetName = GetFullEntitySetName(dbContext, entityType); var entityKey = new EntityKey(entitySetName, new[] { new EntityKeyMember(keyPropertyName, keyValue) }); return(entityKey); }
public void Delete() { try { using (var cont = new healthychefEntities()) { System.Data.EntityKey key = cont.CreateEntityKey("hccProgramDefaultMenus", this); object oldObj; if (cont.TryGetObjectByKey(key, out oldObj)) { cont.hccProgramDefaultMenus.DeleteObject((hccProgramDefaultMenu)oldObj); } cont.SaveChanges(); } } catch { throw; } }
/// <summary> /// 更新数据数据库中的一条数据 根据主键值 /// </summary> /// <param name="model"></param> /// <returns></returns> public void Modify(T model) { //.Net 3.5支持的方法 //EntityKey key = context.CreateEntityKey("BlogArticle", model); //object orgData; //if (context.TryGetObjectByKey(key, out orgData)) //{ // context.ApplyPropertyChanges(key.EntitySetName, model); // context.SaveChanges(); // return true; //} //return false; //.Net 4.0支持的方法 System.Data.EntityKey key = context.CreateEntityKey((context.CreateObjectSet <T>()).EntitySet.Name, model); object orgData; if (context.TryGetObjectByKey(key, out orgData)) { context.ApplyCurrentValues(key.EntitySetName, model); } }
public void UpdateItem(IItemModel t) { try { using (ItemEntities context = ItemEntities.Instance()) { System.Data.EntityKey pKey = ((Item)t).EntityKey; if (pKey != null) { object pObject; if (context.TryGetObjectByKey(pKey, out pObject)) { context.ApplyPropertyChanges(pKey.EntitySetName, (Item)t); } } context.SaveChanges(); } DataCache.RemoveCache(itemCacheKey(t.ModuleId)); } catch (Exception ex) { Exceptions.LogException(ex); } }
/// <summary> /// Checks if a property is the key we want to set the value on. /// Do this by instantiating the foreign key reference class and getting its primary key. /// We then compare the primary key name with linqPropertyName to see if this is the key we want to set the value on. /// </summary> /// <param name="obj">Entity Framework class containing the foreign key references</param> /// <param name="linqPropertyName">Name of foreign key field to set value on (Foreign Class's primary key)</param> /// <param name="propertyValue">Value to set for foreign key</param> /// <param name="entityObjectProperty">Foreign key Entity Framework class, ie: MyForeignTable</param> /// <param name="entityReferenceProperty">Foreign key EntityReference class, ie: MyForeignTableReference</param> /// <returns>true if value was successfully set for foreign key</returns> private static bool SetPropertyValueEntityReference(object obj, string linqPropertyName, object propertyValue, PropertyInfo entityObjectProperty, PropertyInfo entityReferenceProperty) { // Get the EntityReference object (ForeignKeyReference). object val = entityReferenceProperty.GetValue(obj, null); // Get the existing value for the foreign key. System.Data.EntityKey entityKey = ((System.Data.Objects.DataClasses.EntityReference)(val)).EntityKey; // Get the type of the foreign key class. Type foreignKeyType = entityObjectProperty.PropertyType; // Get it's constructor ConstructorInfo foreignKeyConstructor = foreignKeyType.GetConstructor(new Type[] { }); // Invoke it's constructor, which returns an instance of the foreign key class. object foreignKey = foreignKeyConstructor.Invoke(new object[] { }); var primaryKeyForeignKey = (from p in foreignKey.GetType().GetProperties() from attr in p.GetCustomAttributes(false) where attr is System.Data.Objects.DataClasses.EdmScalarPropertyAttribute && ((attr as System.Data.Objects.DataClasses.EdmScalarPropertyAttribute).EntityKeyProperty && !(attr as System.Data.Objects.DataClasses.EdmScalarPropertyAttribute).IsNullable) select p).FirstOrDefault(); if (primaryKeyForeignKey.Name == linqPropertyName) { // This is the property we want to set the value on. // Get the EntityKey for the foreign key. PropertyInfo entityKeyProperty = ((System.Data.Objects.DataClasses.EntityReference)(val)).GetType().GetProperty("EntityKey"); object currentValue = null; System.Data.EntityKey entityKeyObj = (System.Data.EntityKey)entityKeyProperty.GetValue(val, null); if (entityKeyObj != null) { currentValue = entityKeyObj.EntityKeyValues[0].Value; } if (currentValue == propertyValue || (currentValue != null && currentValue.Equals(propertyValue))) { // Value has not changed. } else { // If the foreign key has a value, we need to set it to null before assigning a new value. if (entityKey != null) { // The foreign key already has a value. First set it to null, then we'll assign the new value. entityKey = null; entityKeyProperty.SetValue(val, entityKey, null); } // If the foreign key is being assigned a null value, then we're done. Otherwise, set the value. if (propertyValue != null) { // Create an EntityKey to hold the foreign key's value. Instantiate EntityKey. Type entityType = typeof(System.Data.EntityKey); // Get it's constructor ConstructorInfo constructor = entityType.GetConstructor(new Type[] { typeof(string), typeof(string), typeof(object) }); // Setup the naming structure for the EntityKey. string dbContextName = ((System.Data.Objects.DataClasses.EntityObject)(obj)).EntityKey.EntityContainerName; string entityKeyName = ((System.Data.Objects.DataClasses.RelatedEnd)(val)).TargetRoleName; string targetKey = dbContextName + "." + entityKeyName; // Invoke it's constructor, which returns an instance of the EntityKey. object entityRef = constructor.Invoke(new object[] { targetKey, linqPropertyName, propertyValue }); // Set the value for the foreign key. entityKeyProperty.SetValue(val, entityRef, null); } } return(true); } return(false); }
public static object ConvertToBusinessObject <TEntity1>(TEntity1 originalObject, object abusinessType) { // Convert originalObject to a businessType object. object businessObject = null; Type businessType = originalObject.GetType(); PropertyInfo lastProperty = null; bool foreignKeyReference = false; // Find the class Type obj = Type.GetType(businessType.AssemblyQualifiedName); // Get it's constructor ConstructorInfo constructor = obj.GetConstructor(new Type[] { }); // Invoke it's constructor, which returns an instance of businessType. businessObject = constructor.Invoke(null); PropertyInfo[] propInfo = abusinessType.GetType().GetProperties(); foreach (PropertyInfo property in propInfo) { string key = property.Name; object value = null; foreignKeyReference = false; if (!property.PropertyType.IsArray || property.PropertyType.Name.ToLower() == "byte[]") { if (property.PropertyType.Name.IndexOf("EntityReference") > -1) { // This is an EntityFramework foreign key. Set the value, if one exists. Otherwise, it defaults to null. System.Data.EntityKey entityKey = ((System.Data.Objects.DataClasses.EntityReference)(property.GetValue(abusinessType, null))).EntityKey; if (entityKey != null) { foreignKeyReference = true; key = entityKey.EntityKeyValues[0].Key; value = ((System.Data.Objects.DataClasses.EntityReference)(property.GetValue(abusinessType, null))).EntityKey.EntityKeyValues[0].Value; } } else { value = property.GetValue(abusinessType, null); } // Grab any AlternateName attribute from the property. string alternateKey = ""; string linqContextPropertyName = ""; bool foreignKeyReferenceProcessed = false; // If we're doing a Set (for example: table.ForeignId = N) then setup the proper mapping. object[] attributes = property.GetCustomAttributes(false); foreach (object attribute in attributes) { if (attribute is AlternateMappingAttribute) { alternateKey = ((AlternateMappingAttribute)attribute).ForeignKeyName; linqContextPropertyName = ((AlternateMappingAttribute)attribute).LinqPropertyName; foreignKeyReferenceProcessed = true; // For referenced foreign keys, make sure it has a value to set, otherwise leave null. if (value != null && (value.ToString().Length == 0 || value.ToString() == "0" || value.ToString() == Guid.Empty.ToString())) { value = null; } } } // If we're doing a Get (for example: table.Load(N) where table contains a ForeignId) then setup the proper mapping. if (foreignKeyReference && !foreignKeyReferenceProcessed) { bool doneMapping = false; // Find the foreign key property name in our business type that also has an AlternateMappingAttribute. PropertyInfo[] propInfo2 = businessType.GetProperties(); foreach (PropertyInfo property2 in propInfo2) { object[] attributes2 = property2.GetCustomAttributes(false); foreach (object attribute in attributes2) { if (attribute is AlternateMappingAttribute) { if (((AlternateMappingAttribute)attribute).LinqPropertyName == lastProperty.Name) { // We've found a mapping property. Change the key to set to be the alternateKey. alternateKey = property2.Name; linqContextPropertyName = ((AlternateMappingAttribute)attribute).LinqPropertyName; key = alternateKey; // For referenced foreign keys, make sure it has a value to set, otherwise leave null. if (value != null && (value.ToString().Length == 0 || value.ToString() == "0" || value.ToString() == Guid.Empty.ToString())) { value = null; } doneMapping = true; break; } } } if (doneMapping) { break; } } } SetPropertyValue(originalObject, key, value, alternateKey, linqContextPropertyName); } // Record the last property to use with foreign key lookups. lastProperty = property; } return(businessObject); }