Entity Framework - Attaching Entities - Attach Navigation Properties?

爱⌒轻易说出口 提交于 2019-12-23 16:04:03

问题


I have the following generic code to update a disconnected entity:

public T UpdateItem(T entity)
{
    this._dbSet.Attach(entity);
    this._dbContext.Entry(entity).State = System.Data.EntityState.Modified;

    this._dbContext.SaveChanges();

    return entity;
}

If my entity contains navigation properties, those do not get attached and set to modified. Is there a way I can change this generic method to attach and set to modified, all navigation properties as well?


回答1:


You can do it with reflection. Here's an extension method to find all the related collections. If all of your Entities implement some standard interface you'll be able to make a similar method to find the non collection navigation properties (that implement your interface).

public static class ContextExtensions
{
    public static IEnumerable<IEnumerable<dynamic>> GetCollections(this object o)
    {
        var result = new List<IEnumerable<dynamic>>();
        foreach (var prop in o.GetType().GetProperties())
        {
            if (typeof(IEnumerable<dynamic>).IsAssignableFrom(prop.PropertyType))
            {
                var get = prop.GetGetMethod();
                if (!get.IsStatic && get.GetParameters().Length == 0)
                {
                    var enumerable = (IEnumerable<dynamic>)get.Invoke(o, null);
                    if (enumerable != null) result.Add(enumerable);
                }
            }
        }
        return result;
    }
}

This should add the current objects navigation properties

var collections = entity.GetCollections();
foreach (var collection in collections)
{
    foreach (var r in collection)
    {
        if (_this._dbSet.Entry(r).State == System.Data.EntityState.Detached)
        {
            this._dbSet.Attach(r);
            this._dbContext.Entry(r).State = System.Data.EntityState.Modified;
        }
    }
}


来源:https://stackoverflow.com/questions/16419773/entity-framework-attaching-entities-attach-navigation-properties

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!