开发者

Can't update rows in my database using Entity Framework...?

开发者 https://www.devze.com 2022-12-30 15:42 出处:网络
Okay, this is really weird. I made a simple database with a single table, Customer, which has a single column, Name. From the datab开发者_StackOverflow中文版ase I auto-generated an ADO.NET Entity Data

Okay, this is really weird. I made a simple database with a single table, Customer, which has a single column, Name. From the datab开发者_StackOverflow中文版ase 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!?


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


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


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


Make sure that the "Copy to Output Directory" property of the database file is not set to "Copy always." If it is, every time you rebuild the application, the database may be clobbered with a pristine copy.

See: Entity Framework not flushing data to the database

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号