我试图按照本指南从引导嘲讽实体框架嘲讽实体框架给了我对象没有设置到
https://msdn.microsoft.com/en-us/library/dn314429.aspx
代码工作绝对没问题,当我建立一个对象的实例它在我的项目,但是当我试图把它应用到我的实际情况和数据对象,我发现了一个异常:未设置为一个对象的实例
对象引用
我的目标很简单:
public class NodeAttributeTitle
{
public int ID { get; set; }
[MaxLength(150)]
public string Title { get; set; }
public string Description { get; set; }
}
因为是我的上下文
public class DataContext : DbContext
{
public virtual DbSet<NodeAttributeTitle> NodeAttributeTitles { get; set; }
}
,我尝试设置方法只是一个基本的插入
public class CommonNodeAttributes : ICommonNodeAttributes
{
private DataContext _context;
public CommonNodeAttributes(DataContext context)
{
_context = context;
}
public CommonNodeAttributes()
{
_context = new DataContext();
}
public void Insert(string value)
{
var nodeAttributeValue = new NodeAttributeValue();
nodeAttributeValue.Value = value;
nodeAttributeValue.Parent = 0;
_context.NodeAttributeValues.Add(nodeAttributeValue);
_context.SaveChanges();
}
}
而且该测试课程遵循与MSDN指南中相同的语法
[TestClass]
public class CommonNodeAttributesTests
{
[TestMethod]
public void CreateNodeAttribute_saves_a_nodeattribute_via_context()
{
var mockSet = new Mock<DbSet<NodeAttributeTitle>>();
var mockContext = new Mock<DataContext>();
mockContext.Setup(m => m.NodeAttributeTitles).Returns(mockSet.Object);
var service = new CommonNodeAttributes(mockContext.Object);
service.Insert("blarg");
mockSet.Verify(m => m.Add(It.IsAny<NodeAttributeTitle>()),Times.Once());
mockContext.Verify(m => m.SaveChanges(),Times.Once);
}
}
和测试运行时呢,我得到
Tests.CommonNodeAttributesTests.CreateNodeAttribute_saves_a_nodeattribute_via_context抛出异常:
System.NullReferenceException:未设置为一个对象的实例对象引用。
我不明白为什么指南中的代码工作正常,但我的代码没有。
我已经尝试在ID,标题和描述属性中添加'虚拟',但这也不会执行任何操作。有没有人对我有什么不同的线索?
可能重复[什么是NullReferenceException,以及如何解决它?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-doi-i-修理它) –