简体   繁体   English

无法使用Entity Framework更新数据库中的行…?

[英]Can't update rows in my database using Entity Framework…?

Okay, this is really weird. 好吧,这真的很奇怪。 I made a simple database with a single table, Customer, which has a single column, Name. 我用一个表Customer创建了一个简单的数据库,该表有一个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: 从数据库中,我自动生成了一个ADO.NET实体数据模型,并且我正在尝试向其添加新客户,如下所示:

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! 但是,它不会将客户“ Harry”保留到数据库中! 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. EF要求您对许多操作都有唯一的索引。

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? app.config文件中是否有连接字符串?
  • Do you have more than one project in your solution? 您的解决方案中是否有多个项目?
  • Are you getting any exceptions? 你有什么例外吗?

Edit2: 编辑2:

Next things to try: 接下来的尝试:

  • Use SQL Server profiler to see what is being sent to the database 使用SQL Server分析器查看正在发送到数据库的内容
  • Open the EF model in an editor to see the xml, check if there are any errors 在编辑器中打开EF模型以查看xml,检查是否存在任何错误

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 请参阅: 实体框架未将数据刷新到数据库

db放在using语句中,以确保在进程退出之前干净地关闭连接/事务。

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 您可以通过使用SQL Server Management Studio将一些记录添加到测试数据库中进行验证,然后执行类似的操作

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM