我正在从“编程实体框架代码优先”学习EF Code First。以下代码段从第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();
}
}
}
}
不幸的是,我收到了以下错误。你能告诉我出了什么问题吗?
答案 0 :(得分:2)
可能你没有填写所有必填字段。我注意到的是Patient.FirstVisit
sql server不接受默认值。
答案 1 :(得分:1)
不确定这是否是您确切错误的原因,但也可能导致其他错误;您的VetContext
应该还包含1行:
public DbSet<AnimalType> AnimalTypes { get; set; }
否则,EF不会在DB中创建AnimalType
表来插入
var dog = new AnimalType { TypeName = "Dog" };
记录到。