gpt4 book ai didi

c# - Entity Framework 如何只更新模型中的特定字段?

转载 作者:太空宇宙 更新时间:2023-11-03 11:10:44 26 4
gpt4 key购买 nike

我发布了这个问题,但有人哄堂大笑,我改写了我的实际问题并刚刚发布了代码,然后它被投票关闭。我想到了这个问题几乎是 fubared 并且没有得到公平的震动,所以我再次发布它。

我正在使用 Entity Framework 4.1。我有一个表格,上面有很多字段。表格本身实际上比表格上的字段更多。我试图找到一种方法来更新已更改的字段。我在这里找到了一个例子:

EntityFramework update partial model

我已将其修改为以下代码,这样我就不必手动指定 40 多个字段。我希望有一种比下面的方法更简洁的方法来做到这一点。有吗?

警告下面的代码是初稿,相当粗糙。欢迎所有建议。谢谢!

    [HttpPost]
public ActionResult Edit(Location location, FormCollection fields)
{
if (ModelState.IsValid)
{
//db is my context
db.Locations.Attach(location);

StringBuilder sb = new StringBuilder();

//Get properties of Location object
PropertyInfo[] pi = typeof(Location).GetProperties();

//loop over keys of fields submitted by the post
foreach (string submittedField in fields.Keys)
{
//If a property name on the Location object matches a field name
//of one of the submitted properties then mark the property as
//modified
if (pi.Any(prop => prop.Name.Equals(submittedField)) &&
!"ID".Equals(submittedField) )
{
db.Entry(location).Property(submittedField).IsModified = true;
sb.AppendLine(submittedField + "Value: " + db.Entry(location).Property(submittedField).CurrentValue );
}
}

LogUtil.WriteCondensed(sb.ToString());

//Save changes to the database
db.SaveChanges();
return RedirectToAction("Index");
}
return View(location);
}

最佳答案

出于安全原因,我不会依赖传递给您的 Edit 操作的内容来了解​​可以更新的内容和不能更新的内容(请记住,客户端可以更改发布到服务器的内容)。

public class YourEntity
{
public long ID { get; set; }

// Updatable fields
public string Field1 { get; set; }
....
}

在 View 中,为要更新的对象的 ID 使用隐藏字段(razor 语法):

@model YourEntity
...
@Html.HiddenFor(model => model.ID)
...
@Html.EditorFor(model => model.Field1)

然后我会:

  1. 检查用户是否有权更新实体
  2. 使用 ID 从数据库中检索实际实体
  3. 按属性手动更新属性
  4. 保存到数据库

Controller :

[HttpPost]
public ActionResult Edit(YourEntity model)
{
try
{
yourServiceLayer.Update(User.Identity.Name, model);
}
catch (CustomSecurityException)
{
...
}
}

服务:

public class YourServiceLayer
{
public YourEntity Update(string userName, YourEntity entity)
{
// Check user has rights to edit the entity (if necessary)
if (this.CanUpdate(userName, entity.ID))
{
// Gets actual entity from DB
var yourDbEntity = this.GetByID(entity.ID);

// Updates each property manually
yourDbEntity.Field1 = entity.Field1;
....

// Saves to DB
this.Save(yourDbEntity);
return yourDbEntity;
}
else
{
// Security exception
throw new CustomSecurityException(...);
}
}

public bool CanUpdate(string userName, long entityID)
{
// Insert logic here
return ....;
}

...
}

如果你有 40 多个字段,那么是的,写起来很无聊,但至少你可以完全控制可以更新的属性和不能更新的属性。

关于c# - Entity Framework 如何只更新模型中的特定字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14139344/

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