gpt4 book ai didi

entity-framework - Entity Framework - 附加实体 - 附加导航属性?

转载 作者:行者123 更新时间:2023-12-01 10:54:10 30 4
gpt4 key购买 nike

我有以下通用代码来更新断开连接的实体:

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

this._dbContext.SaveChanges();

return entity;
}

如果我的实体包含导航属性,则这些属性不会被附加并设置为已修改。有没有一种方法可以更改此通用方法以附加并设置为已修改的所有导航属性?

最佳答案

你可以通过反射(reflection)来做到这一点。这是查找所有相关集合的扩展方法。如果您的所有实体都实现了一些标准接口(interface),您将能够使用类似的方法来查找非集合导航属性(实现您的接口(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;
}
}

这应该添加当前对象的导航属性

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;
}
}
}

关于entity-framework - Entity Framework - 附加实体 - 附加导航属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16419773/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com