[英]Failed to save changes with EF DbContext
我正在從“編程實體框架代碼優先”中學習EF代碼優先。 以下代碼段從第5頁復制到第7頁。
using System;
namespace ChapterOne
{
class Visit
{
public int Id { get; set; }
public DateTime Date { get; set; }
public String ReasonForVisit { get; set; }
public String Outcome { get; set; }
public Decimal Weight { get; set; }
public int PatientId { get; set; }
}
}
namespace ChapterOne
{
class AnimalType
{
public int Id { get; set; }
public string TypeName { get; set; }
}
}
using System;
using System.Collections.Generic;
namespace ChapterOne
{
class Patient
{
public Patient()
{
Visits = new List<Visit>();
}
public int Id { get; set; }
public string Name { get; set; }
public DateTime BirthDate { get; set; }
public AnimalType AnimalType { get; set; }
public DateTime FirstVisit { get; set; }
public List<Visit> Visits { get; set; }
}
}
using System.Data.Entity;
namespace ChapterOne
{
class VetContext : DbContext
{
public DbSet<Patient> Patients { get; set; }
public DbSet<Visit> Visits { get; set; }
}
}
using System;
using System.Collections.Generic;
namespace ChapterOne
{
class Program
{
static void Main(string[] args)
{
var dog = new AnimalType { TypeName = "Dog" };
var patient = new Patient
{
Name = "Simpson",
BirthDate = new DateTime(2008, 1, 28),
AnimalType = dog,
Visits = new List<Visit>
{
new Visit
{
Date = new DateTime(2011, 9, 1)
}
}
};
using (var context = new VetContext())
{
context.Patients.Add(patient);
context.SaveChanges();
}
}
}
}
不幸的是,我收到以下錯誤。 你能告訴我有什么問題嗎?
可能你沒有填寫所有必填字段。 我注意到的一個是Patient.FirstVisit
默認值是sql server不能接受的。
不知道這是否是造成您確切錯誤的原因,但也可能會導致另一個錯誤; 您的VetContext
應該包含1行:
public DbSet<AnimalType> AnimalTypes { get; set; }
否則,EF不會在數據庫中創建AnimalType
表來插入
var dog = new AnimalType { TypeName = "Dog" };
錄入。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.