110,534
社区成员
发帖
与我相关
我的任务
分享
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);
}
}
}
}
private static void SaveInput(string question, string answer)
{
using (var ctx = new AnswersContext())
{
var answer=new Answer() { Content = answer };
ctx.Answers.Add(answer); ////// :(
ctx.SaveChanges();
ctx.Questions.Add(new Question()
{
Content = question,
Answers = { answer },
});
ctx.SaveChanges();
}
}
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();
}
}