EF实例问题.做到一半.提示未将引用设置到对象的实例.
class Question
{
public int Id { get; set; }
public string Content { get; set; }
public virtual ICollection<Answer> Answers { get; set; }
}
class Answer
{
public int Id { get; set; }
public string Content { get; set; }
public virtual Question Question { get; set; }
}
class AnswersContext : DbContext
{
public DbSet<Question> Questions { get; set; }
public DbSet<Answer> Answers { get; set; }
}
internal class Program
{
static void Main(string[] args)
{
DoWork();
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
}
static void DoWork()
{
Console.WriteLine("===Please enter five Questions and Answers===");
for (int i = 0; i < 5; i++)
{
Console.WriteLine("Enter the Question:");
string question = Console.ReadLine();
Console.WriteLine("Enter the Answer:");
string answer = Console.ReadLine();
Console.WriteLine("Saving entry...");
SaveInput(question, answer);
}
PrintQuestions();
}
private static void SaveInput(string question, string answer)
{
using (var ctx = new AnswersContext())
{
ctx.Questions.Add(new Question()
{
Content = question,
Answers = { new Answer() { Content = answer } }
});
ctx.SaveChanges();
}
}
private static void PrintQuestions()
{
using (var ctx = new AnswersContext())
{
foreach (var q in ctx.Questions)
{
Console.WriteLine(q.Content);
foreach (var a in q.Answers)
{
Console.WriteLine(" -" + a.Content);
}
}
}
}
原文地址:
http://msdn.microsoft.com/en-us/data/jj819165
运行到 ctx.Questions.Add( 就提示未将引用设置到对象的实例了.以往这提示一般是某个对象是null的未实例化.
但我断点看都有数据呀.只是数据库好像没有生成.
1.EF的code first是要到什么步骤才会生成数据库?(实例文章上说写好类就按F5,main方法里还是空的.我按了也没生成)
2.这个错误是我哪里错了?大神指教下.谢谢
(我环境是vs2012+.net4.5+EF6最新装的) --------------------编程问答-------------------- 因为你引用的外键表Answer是空的
private static void SaveInput(string question, string answer)--------------------编程问答--------------------
{
using (var ctx = new AnswersContext())
{
var answer=new Answer() { Content = answer };
ctx.SaveChanges();
ctx.Questions.Add(new Question()
{
Content = question,
Answers = { answer },
});
ctx.SaveChanges();
}
}