EF代码首先:模型配置
-
25-10-2019 - |
题
我会尽可能清楚:
我的目标是:阅读我在被覆盖中声明的模型配置 OnModelCreating
在我的实体课程中衍生 DbContext
.
原因:建立通用 void Update<T>(T toUpdate)
在我的数据层上,我得到哪些字段是t的主要键 toUpdate
反对并在 Set<T>().Find
方法。
这将使我无法为我处理的每种实体找到逻辑。
我需要检索存储的实体以应用更新,例如:
var retrievedItem = _entities.Set<T>().Find(myRetrievedKeyValues);
_entities.Entry(retrievedItem).CurrentValues.SetValues(toUpdate);
我被困在我的 _entities
实例(这是我的实体类 DbContext
当然)我似乎找不到模型配置存储的位置。
有人可以将我指向正确的方向吗?
谢谢。
解决方案
您可以找到代码如何检索实体类型的关键属性名称 YourEntity
这里:
然后检索值:
public Update<T>(T toUpdate)
{
// Code from link above with YourEntity = T
List<object> myRetrievedKeyValues = new List<object>();
foreach (var keyName in keyNames)
myRetrievedKeyValues.Add(toUpdate.GetType().GetProperty(keyName)
.GetValue(toUpdate, null));
var retrievedItem = _entities.Set<T>().Find(myRetrievedKeyValues.ToArray());
_entities.Entry(retrievedItem).CurrentValues.SetValues(toUpdate);
}
预计你会很慢 Update
方法是因为您必须将反射用于这种通用方法。
也不要忘记 CurrentValues.SetValues
仅更新标量和复杂属性。它无助于您更新导航属性。您将必须使用非传播代码来更新针对每个实体类型的关系。
不隶属于 StackOverflow