实体框架错误. [英] Entity Framework error.

查看:69
本文介绍了实体框架错误.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是错误:存储更新,插入或删除语句影响了意外的行数(0).自加载实体以来,实体可能已被修改或删除.

我一直收到此错误,但我知道这段代码应该可以工作.我正在使用一个按钮将数据插入SQL数据库.任何人有任何建议,这是我的代码?


Here''s the error: Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded.

I keep getting this error, but I know this code should work. I am using a button to insert the data into a SQL database. Anyone got any suggestions, here''s my code?


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using USBatchDataModel;

public partial class _Default : System.Web.UI.Page
{
    USBatchDataEntities db = new USBatchDataEntities();
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void ButtonIn_Click(object sender, EventArgs e)
    {
        Contact con = new Contact();
        con.id = Convert.ToInt32(TextBox1.Text);
        con.fname = TextBox2.Text;
        con.lname = TextBox3.Text;
        con.phone = TextBox4.Text;
        db.Contacts.AddObject(con);
        db.SaveChanges(); 
       
    }

推荐答案

尝试以下操作:


尝试{
context.SaveChanges();
} catch(OptimisticConcurrencyException){
context.Refresh(RefreshMode.ClientWins,db.Contacts);
context.SaveChanges();
}
try this:


try {
context.SaveChanges();
} catch (OptimisticConcurrencyException) {
context.Refresh(RefreshMode.ClientWins, db.Contacts);
context.SaveChanges();
}


您可以尝试在方法中将USBatchDataEntities db = new USBatchDataEntities();实例化为最接近需要的地方,而不是您使用的方式.
You could try instantiating USBatchDataEntities db = new USBatchDataEntities(); in the method as close to where you need it rather than the way you have done it.


这篇关于实体框架错误.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆