GEORGI DIMITROV
GEORGI DIMITROV

Reputation: 134

Validation error in Entity framework when inserting data into the database

I am trying to insert classifications data into a Classifications table in my database with Entity framework. The issue is that it gives me this error:

{"Validation failed for one or more entities. See 'EntityValidationErrors' property for more details."}

This is my code:

 public class Classifications
    {
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        [Required]
        public virtual int id { get; set; }

        [Required]
        [MaxLength(250)]
        public virtual string Classification { get; set; }

        [ForeignKey("Movie")]
        [Required]
        public virtual List<Movie> Movies { get; set; }
        [Required]
        public virtual List<Series> Series { get; set; }
        [Required]
        public virtual List<Preference> Preferences { get; set; }
}

and here is my method for adding classifications:

 public static void InsertClassification(string name)
        {
            try
            {
                var classification = new Classifications() { Classification = name };
                using (var db = new DatabaseContext())
                {
                    db.Classifications.Add(classification);
                    db.SaveChanges();
                    Console.WriteLine("Added Classification");
                }
            }catch(Exception ex)
            {
                Console.WriteLine("Cound not add classification");
            }
        }

The error is being given on the db.saveChanges(). With debug it checks this method but instead to print the added data message it goes to the Exception.

I am running it on my Main methoh.

 class Program
    {
        static void Main(string[] args)
        {
           string name = "ClassificationTest";
           Classifications.InsertClassification(name);


        }
    }

Can somebody help me solve this issue ?

Upvotes: 1

Views: 536

Answers (1)

Serge
Serge

Reputation: 43870

You have to remove Required for this properties or create these lists before SaveChanges()

 [ForeignKey("Movie")]
        [Required]
        public virtual List<Movie> Movies { get; set; }
        [Required]
        public virtual List<Series> Series { get; set; }
        [Required]
        public virtual List<Preference> Preferences { get; set; }
}

Upvotes: 2

Related Questions