kiss my armpit
kiss my armpit

Reputation: 3519

Failed to save changes with EF DbContext

I am learning EF Code First from "Programming Entity Framework Code First". The following code snippets are copied from page 5 to page 7.

Visit.cs

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; }
    }
}

AnimalType.cs

namespace ChapterOne
{
    class AnimalType
    {
        public int Id { get; set; }
        public string TypeName { get; set; }
    }
}

Patient.cs

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; }
    }
}

VetContext.cs

using System.Data.Entity;

namespace ChapterOne
{
    class VetContext : DbContext
    {
        public DbSet<Patient> Patients { get; set; }
        public DbSet<Visit> Visits { get; set; }
    }
}

Program.cs

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?

enter image description here

Upvotes: 1

Views: 784

Answers (2)

Piotr Auguscik
Piotr Auguscik

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

CodingWithSpike
CodingWithSpike

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

Related Questions