实体框架 - 如何更新,从键 - 值对的列表领域? [英] Entity Framework - How to update fields from a list of key-value pairs?
问题描述
假设用户修改自己的包含如名字,姓氏,电子邮件等领域的资料记录。
Let's say the user modifies his profile record that contains fields such as FirstName, LastName, Email, etc.
有关被修改,变更存储为一个键值对的类型的列表中的每个字段:
For each field that is modified, the change is stored as a key-value pair in a list of type:
List<Tuple<string, object>>
在此键值对重$ P $关键psents实际的表列。
The key in this key-value pair represents the actual table column.
在尝试更新记录,这里是如何做这件事的方式:
While trying to update the record, here is one way to do it:
foreach (Tuple<string, object> field in changeList) {
if (field.Item1.equals("FirstName")) {
user.FirstName = field.Item2;
}
if (field.Item1.equals("Email")) {
user.Email = field.Item2;
}
...
}
db.SaveChanges()
我想必须有一个更好的方式来做到这一点。
I am thinking there must be a better way to accomplish this.
我想我可以使用反射来对用户设置每个属性
I guess I could use reflection to set each property on the user
foreach(tuple<string, object> field in changeList) {
user.GetType().InvokeMember(field.Item1,
BindingFlags.Instance | BindingFlags.Public | BindingFlags.SetProperty,
Type.DefaultBinder, user, field.Item2);
}
我想知道是否有更好的方法。也许我可以动态地构建一个变种的对象,也将让我用TryUpdateModel()方法。
I am wondering if there is even better way. Perhaps I could build a "var" object dynamically that will also let me use TryUpdateModel() method.
推荐答案
我做了类似的事情,但使用string类型和对象的自定义对象。我也不知道这是否是有效率的,但它能够完成任务。为了证明我已经使用元组,其中第一ITEM1是字符串,项目2是一个对象。
I have done something similar but using a custom object of type string and object. I also don't know if this is the efficient one but it gets the job done. To demonstrate I have used Tuple where first item1 is string and item2 is an object.
List<Tuple<string, object>> listTuple = new List<Tuple<string, object>>();
listTuple.Add(new Tuple<string, object>("FirstName", "Foo"));
listTuple.Add(new Tuple<string, object>("LastName", "Bar"));
PropertyInfo[] props = user.GetType().GetProperties();
foreach (var prop in props)
{
if (prop.PropertyType.Name == "ICollection`1")
{
//Do not do anything these are navigation properties in entity framework.
//For eg. If User has Applications then do not set values for Applications.
}
else
{
//Match each property with matching Item1 in Tuple.
var myTuple = listTuple.Where(x => x.Item1 == prop.Name).First();
//Set Users Property using myTuple's Item2 which is an object here.
prop.SetValue(user, myTuple.Item2, null);
}
}
这篇关于实体框架 - 如何更新,从键 - 值对的列表领域?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!