问题描述
我有一个名为ABC的实体的EntityFramework(属性ID和标题)。
在更新记录来看,我已经添加了ID为隐藏字段标题文本框。
控制器看起来像:
公众的ActionResult UpdateAction(ABC OBJ)
我得到的一切罚款和OBJ公平 - 即标题,ID
现在来更新数据库中的记录,我读了原始的实体:
VAR原=(从X在base.context.ABC那里x.id == obj.id)。单();
现在,以反映原的变化,我觉得应该做的更新模型:
this.TryUpdateModel(原件);
我得到一个错误:| ...说明列ID不能更改。
属性ID是对象的关键信息的一部分,不能进行修改。
我不想手动分配的属性回原来的对象。
另一种方法可以是:
TryUpdateModel(原件,新的String [] {标题},form.ToValueProvider());
但我讨厌琴弦 - 还有,我的对象具有类似于20属性:|
有人能提出这样做的更好的模式?
RGDS
公共类ControllerExt:控制器
{
保护无效的UpdateModel<&的TModel GT;(的TModel模型,则params防爆pression<&Func键LT;的TModel,对象>> []属性),其中的TModel:类
{
VAR道具=新的List<串GT;(property.Length);
的foreach(物业VAR P)
{
VAR memberEx pression = RemoveUnary(p.Body)作为MemberEx pression;
如果(memberEx pression == NULL)
{
抛出新的NullReferenceException(无法检索{0}的成员信息FormatThis(typeof运算(的TModel).Name点));
}
props.Add(memberEx pression.Member.Name);
}
this.UpdateModel(模型,props.ToArray());
} 私有静态防爆pression RemoveUnary(前pression体)
{
VAR一元=身体UnaryEx pression;
如果(一元!= NULL)
{
返回unary.Operand;
}
回体;
}
}
例如:
的UpdateModel<&为MyModel GT;(模型,X => x.PropertyFromMyModel_1,X => x.PropertyFromMyModel_2);
I have an entityframework entity called "ABC" (attributes ID and Title).
On update record view, I have added the ID as hidden field and title is the text box.
Controller looks like something:
public ActionResult UpdateAction( ABC obj )
I get everything fine and fair in obj - i.e., the title, and the ID.
Now to update the record in database, I read the original entity:
var original = (from x in base.context.ABC where x.id == obj.id ).Single();
Now to reflect the changes in original, I think should do the update model:
this.TryUpdateModel( original );
I get an error :| ... stating that column ID cannot be changed.
The property 'id' is part of the object's key information and cannot be modified.
I do not want to manually assign the properties back to original object.
The other alternative can be:
TryUpdateModel(original, new string[] { "Title" }, form.ToValueProvider());
But I hate strings - also, my object has like 20 attributes :|
Can someone please suggest a better pattern of doing so?
Rgds
public class ControllerExt : Controller
{
protected void UpdateModel<TModel>(TModel model, params Expression<Func<TModel, object>>[] property) where TModel : class
{
var props = new List<string>(property.Length);
foreach (var p in property)
{
var memberExpression = RemoveUnary(p.Body) as MemberExpression;
if (memberExpression == null)
{
throw new NullReferenceException("Can not retrieve info about member of {0}".FormatThis(typeof(TModel).Name));
}
props.Add(memberExpression.Member.Name);
}
this.UpdateModel(model, props.ToArray());
}
private static Expression RemoveUnary(Expression body)
{
var unary = body as UnaryExpression;
if (unary != null)
{
return unary.Operand;
}
return body;
}
}
Example:
UpdateModel<MyModel>(model, x => x.PropertyFromMyModel_1, x => x.PropertyFromMyModel_2);
这篇关于编辑和更新实体框架实体ASP .NET MVC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!