Entity Framework 5.0 throwing EntityException when trying to add row to SQLServer Database

I'm making a small Entity Framework based console application where I'm trying to access an SQLServer database I have stored in my computer and Add a row to one of it's tables. Thing is when I try and run the program the db.SaveChanges(); method throws an EntityException, and even after I surround it with try/catch and the code works without any compilation errors, the data is not saved in the database and it goes into the catch code and writes the line "Didn't work". Here's the code:

using System;
using System.Collections.Generic;
using System.Data.Entity.Core;
using System.Linq;
using System.Text;
using System.Threading.Tasks;


namespace ConsoleAchei
{
    class Program
    {
        static void Main(string[] args)
        {
            using (var db = new AcheiEntities2())
            {

                var cliente = new Cliente()
                {
                     ID = 1,
                    NOME = "Fan 123",
                    EMAIL = "[email protected]",
                    SENHA = "ASHDUASDHUAS"
                };
                try
                {
                    db.Cliente.Add(cliente);
                    db.SaveChanges();
                }
                catch (EntityException e)
                {
                    Console.WriteLine("Didn't work");
                    Console.ReadKey();
                }


            }
        }
    }
}

Connection to the Database is working A-OK. I just don't know why this exception is being thrown. I'm basing myself on this video https://www.youtube.com/watch?v=o-cV_fSNMqw and he doesn't even have to surround it with try/catch. Maybe somekind of compatiblity problem? (Video uses Entity 4.0 and I'm using 5.0). Any help will be much appreciated.

Upvotes: 0

Views: 306

Answers (1)

Leandro Soares
Leandro Soares

Reputation: 2972

EntityException could be anything.

But i would change

var cliente = new Cliente()
{
     ID = 1,
    NOME = "Fan 123",
    EMAIL = "[email protected]",
    SENHA = "ASHDUASDHUAS"
};

to

var cliente = new Cliente()
{
    NOME = "Fan 123",
    EMAIL = "[email protected]",
    SENHA = "ASHDUASDHUAS"
};

Probably you ID is set with SQL Identity and you cannot set it manually

Identity is set by default when you add the Data Annotation [Key] or [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]

Or if you are using Fluent API:

modelBuilder.Entity<Cliente>().Property(s => s.ID).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);

Upvotes: 1

Related Questions