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 = "SDASDAS@gmail.com",
                    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.

Answers


EntityException could be anything.

But i would change

var cliente = new Cliente()
{
     ID = 1,
    NOME = "Fan 123",
    EMAIL = "SDASDAS@gmail.com",
    SENHA = "ASHDUASDHUAS"
};

to

var cliente = new Cliente()
{
    NOME = "Fan 123",
    EMAIL = "SDASDAS@gmail.com",
    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);

Need Your Help

php mb_convert_case() keep words that are in uppercase

php string utf-8 mbstring

Assuming I have a string "HET1200 text string" and I need it to change to "HET1200 Text String". Encoding would be UTF-8.

Make table with for loop

php for-loop html-table

Basically, I am just trying to learn how to generate a table with PHP for loop that lists numbers in sequential order. Something like this: