我在我的MVC Project 4.0中安装了neo4j和neo4jClient。
从指南中安装示例电影数据库
:play movies
我在Web.Config中进行了以下设置:
<appSettings>
<add key="ClientDBUrl" value="http://localhost:7474/db/data" />
<add key="ClientDBUser" value="neo4j" />
<add key="ClientDBPassword" value="password" />
</appSettings>
在App_Start文件夹中制作WbApiConfig.cs
public class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.MapHttpAttributeRoutes();
config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
config.Formatters.JsonFormatter.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
var appXmlType = config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/xml");
config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType);
//Use an IoC container and register as a Singleton
var url = ConfigurationManager.AppSettings["ClientDBUrl"];
var user = ConfigurationManager.AppSettings["ClientDBUser"];
var password = ConfigurationManager.AppSettings["ClientDBPassword"];
var client = new GraphClient(new Uri(url), user, password);
client.Connect();
GraphClient = client;
}
public static IGraphClient GraphClient { get; private set; }
}
创建模型
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}
然后我在控制器中编写简单查询以确定视图中的数据
public ActionResult Index()
{
var query = WebApiConfig.GraphClient.Cypher.Match("(p:Person)-[:ACTED_IN]->(m:Movie {title: 'Top Gun'})")
.Return(p => p.As<Person>()).Results;
return View(query.ToList());
}
并在视野中
@model IEnumerable<Neo4j_TestProject1.Models.Person>
<table>
@foreach (var item in Model) {
<tr>
<td>
@item.Name
</td>
</tr>
}
</table>
但我得到的错误是#34;对象引用未设置为实例&#34;在我的查询中。
答案 0 :(得分:0)
我无法重现错误 - 但是! - 我想我知道你哪里出错了。
Movies
数据集确实有Person
标签,但是如果你看一下,你就会发现只有2个属性born
和name
。因此,您永远不会设置Age
和Id
属性,暂时忽略这些属性,因为您没有查看它们 - 您拥有的Name
属性也没有设置 - 这是因为Neo4j区分大小写。
如果您将Person
课程更改为:
public class Person
{
public int Id { get; set; }
[JsonProperty("name")] // <-- Added
public string Name { get; set; }
public int Age { get; set; }
}
您将获得姓名,您基本上是在告诉Neo4jClient
为您翻译。
您可以将Person
类修改为:
public class Person
{
private int _born;
public int Id { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("born")]
public int Born
{
get => _born;
set
{
_born = value;
Age = DateTime.Now.Date.Year - value;
}
}
public int Age { get; set; }
}
如果你想要它会让你成年!