EntityKey and ApplyPropertyChanges()

前端 未结 5 1302
时光取名叫无心
时光取名叫无心 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

    Improving upon Steve Willcock's great implementation, here's my suggestion.

    It uses Reflection (a part of .NET) way more than the original example, to save you some code. It also automatically supports any type of entity class, and not just a "Department".

    Furthermore, it gets rid of the obsolete ApplyPropertyChanges method, and uses the new ApplyCurrentValues method.

    The method

    The method basically just uses reflection to get the value of the "Id" property dynamically, and setting it too. This saves all the hassle with a delegate.

    public static void ApplyDetachedPropertyChanges(this ObjectContext db, T entity) where T : EntityObject
    {
        PropertyInfo idProperty = typeof(T).GetProperty("Id");
    
        var entitySetName = db.DefaultContainerName + "." + entity.GetType().Name;
        var id = idProperty.GetValue(entity, null);
        var entityKey = new EntityKey(entitySetName, "Id", id);
    
        Type type = entity.GetType();
        EntityObject obj = (EntityObject)Activator.CreateInstance(type);
    
        idProperty.SetValue(obj, id, null);
        obj.EntityKey = entityKey;
    
        db.Attach(obj);
        db.AcceptAllChanges();
    
        db.ApplyCurrentValues(entitySetName, entity);
    }
    

    Usage

    Using it is pretty simple as well.

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Edit(Guid id, Department Model)
    {
        db.ApplyDetachedPropertyChanges(Model);
        db.SaveChanges();
    }
    

提交回复
热议问题