views:

115

answers:

3

Okay, this is really weird. I made a simple database with a single table, Customer, which has a single column, Name. From the database I auto-generated an ADO.NET Entity Data Model, and I'm trying to add a new Customer to it like so:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Test
{
    class Program
    {
        static void Main()
        {
            Database1Entities db = new Database1Entities();
            Customer c = new Customer();
            c.Name = "Harry";
            db.AddToCustomer(c);
            db.SaveChanges();
        }
    }
}

But it doesn't persist Customer "Harry" to the database! I've been scratching my head for a while now wondering why such a simple operation doesn't work. What on earth could be the problem!?

+1  A: 

EF requires that you have a unique index for many operations.

Try adding an identity field (primary key) to your table. Delete and recreate your model and try again.

Edit:

It looks like you are running this from a console app.

  • Do you have a connection string in the app.config file?
  • Do you have more than one project in your solution?
  • Are you getting any exceptions?

Edit2:

Next things to try:

  • Use SQL Server profiler to see what is being sent to the database
  • Open the EF model in an editor to see the xml, check if there are any errors
Shiraz Bhaiji
Name is the primary key. :/
Dissonant
But Shiraz and Hightechrider are saying add an int column with Indentity = Yes as the primary key. It's a best practice and it's more optimized:http://stackoverflow.com/questions/1603472/indexing-performance-bigint-vs-varchar
JohnB
I know that it's best practice. This is just a simple database test. Please see my reply to Hightechrider.And to answer your questions, Shiraz:Yes.No.No.
Dissonant
A: 

Place db in a using statement to ensure the connection/transaction is closed cleanly before process exit.

Stephen Cleary
Nope, doesn't work either. :(
Dissonant
A: 

OK, here's a longshot. Are you sure your connection string is pointing to the right place? And the connection is functioning?

You can verify it by using SQL Server Management Studio to add some records to your test database, and then do something like

foreach (Customer c in db.Customers)
{
    Console.WriteLine(c.Name);
}
LSpencer777