Reputation: 3519
I am learning EF Code First from "Programming Entity Framework Code First". The following code snippets are copied from page 5 to page 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();
}
}
}
}
Unfortunately, I got the following error. Could you tell me what is wrong?
Upvotes: 1
Views: 784
Reputation: 3681
Probably you're not filling all required fields. The one i noticed is Patient.FirstVisit
default value is not acceptable by sql server.
Upvotes: 2
Reputation: 43698
Not sure if this is the cause of your exact error, but will probably cause another error too; Your VetContext
should contain 1 more line:
public DbSet<AnimalType> AnimalTypes { get; set; }
Otherwise, EF won't make an AnimalType
table in the DB to insert the
var dog = new AnimalType { TypeName = "Dog" };
record into.
Upvotes: 1