无法使用实体框架更新数据库中的行...?
好吧,这真的很奇怪。我创建了一个简单的数据库,其中包含一个表 Customer,其中只有一个列 Name。我从数据库自动生成了一个 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();
}
}
}
但它不会将客户“Harry”保留到数据库中!我已经挠头一段时间了,想知道为什么这么简单的操作不起作用。到底是什么问题!?
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!?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
EF 要求您为许多操作拥有唯一索引。
尝试向表中添加身份字段(主键)。删除并重新创建您的模型,然后重试。
编辑:
看起来您正在从控制台应用程序运行它。
Edit2:
接下来要尝试的事情:
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.
Edit2:
Next things to try:
将
db
放在using
语句中,以确保在进程退出之前完全关闭连接/事务。Place
db
in ausing
statement to ensure the connection/transaction is closed cleanly before process exit.好吧,这是一个远景。您确定您的连接字符串指向正确的位置吗?连接正常吗?
您可以通过使用 SQL Server Management Studio 将一些记录添加到测试数据库来验证它,然后执行类似的操作
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
确保数据库文件的“复制到输出目录”属性未设置为“始终复制”。如果是这样,每次重建应用程序时,数据库都可能会被原始副本破坏。
请参阅:实体框架未将数据刷新到数据库
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