c# - 如何使用参数使用官方 Neo4j .Net 驱动程序更新节点属性
问题描述
我想在 asp.net mvc 应用程序中使用 .Net 的 Neo4j 官方驱动程序更新我的模型中的值。我的代码如下:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(string name, Category category)
{
try
{
var oldName = name.ToString();
var newName = category.Name.ToString();
using (var session = _driver.Session())
{
session.WriteTransaction(tx =>
{
tx.Run("Match (a:Category) WHERE a.Name = '$oldName' Set a.Name = '$newName'", new { oldName, newName });
});
}
return RedirectToAction(nameof(Index));
}
catch
{
return View();
}
}
但代码结果没有任何变化。为什么?
型号类:
public class Category
{
public string Name { get; set; }
}
我name
从 View 中的这段代码中获得了价值:
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { name = item.Name/* id=item.PrimaryKey */ }) |
@Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) |
@Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })
</td>
</tr>
}
解决方案
您不需要在查询中用引号将参数括起来 - Neo4j 会为您解决这个问题。
尝试:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(string name, Category category)
{
try
{
var oldName = name.ToString();
var newName = category.Name.ToString();
using (var session = _driver.Session())
{
session.WriteTransaction(tx =>
{
tx.Run("Match (a:Category) WHERE a.Name = $oldName Set a.Name = $newName", new { oldName, newName });
});
}
return RedirectToAction(nameof(Index));
}
catch
{
return View();
}
}
在参数部分,您只需要提供其属性名称与查询中的参数名称匹配的任何对象。在您的示例中,该new { oldName, newName }
部分是创建具有两个属性的匿名 C# 对象的简写,一个被调用oldName
,一个被调用newName
,其值取自您定义的变量。
您可以等效地让一个类代表您的参数:
class MyParams {
public string oldName { get; set; }
public string newName { get; set; }
}
var p = new MyParams { oldname = name, newName = category.Name };
tx.Run("Match (a:Category) WHERE a.Name = $oldName Set a.Name = $newName", p);
我更喜欢匿名对象方法,您的口味可能会有所不同。
推荐阅读
- python - 将数组格式的Json数据转换为类型为字典的列表
- excel - 获取定义范围内搜索条件的列号
- wordpress - Wordpress 自动添加标签
- node.js - 如何在 trello Api 中按用户过滤卡片?
- c# - .net core 解析配置界面
- html - Wordpress 图片来源
- c# - 注入一个类来订阅一个内部事件
- python - 为什么我的 apscheduler 没有解雇我的 heroku worker dyno/app/script?
- css - 如何分享可以改变风格的角度库
- docusignapi - 使用 Docusign API 发送信封时,是否可以在文档上有默认签名?