EntityKey and ApplyPropertyChanges()

前端 未结 5 1301
时光取名叫无心
时光取名叫无心 2020-12-30 14:06

I need to set an EntityObject\'s EntityKey. I know its type and its id value. I don\'t want to query the database unnecessarily.

This works...

//
//         


        
5条回答
  •  天涯浪人
    2020-12-30 14:21

    public static class EfExtensions
    {
        public static void ApplyDetachedPropertyChanges(this ObjectContext db, T entity, Func getIdDelegate)
        where T : EntityObject
        {
            var entitySetName = db.DefaultContainerName + "." + entity.GetType().Name;
    
            T newEntity = Activator.CreateInstance();
            newEntity.EntityKey = db.CreateEntityKey(entitySetName, entity);
    
            Type t = typeof(T);
            foreach(EntityKeyMember keyMember in newEntity.EntityKey.EntityKeyValues) {
                PropertyInfo p = t.GetProperty(keyMember.Key);
                p.SetValue(newEntity, keyMember.Value, null);
            }
    
            db.Attach(newEntity);
            //db.AcceptAllChanges();
    
            db.ApplyPropertyChanges(entitySetName, entity);
        }
    }
    

提交回复
热议问题