简体   繁体   English

无法使用Entity Framework中的savechanges()更新数据库

[英]Unable to update database using savechanges() in Entity Framework

I am trying the Model first approach of Entity Framework. 我正在尝试实体框架的模型优先方法。 I am a newbie to Entity Framework and learning from here and coded the same way. 我是Entity Framework的新手,可以从这里学习并用相同的方式编码。 But I am getting this error 但是我收到这个错误

Unable to update the EntitySet 'Users' because it has a DefiningQuery and no <InsertFunction> element exists in the <ModificationFunctionMapping> element to support the current operation.

the code I am running is: 我正在运行的代码是:

protected void Page_Load(object sender, EventArgs e)
    {

        User use = new User();
        use.First_Name = "Arslan";
        use.Last_Name = "Akbar";
        use.Password = "alone";
        use.Email = "arslan@gmail.com";
        use.Designation = "Head";
        using (CustomersEntities ce = new CustomersEntities())

        {

            //int count = ce.Users.Count();
            //count++;
           // use.Id = count;

            ce.Users.Add(use);
            ce.SaveChanges();
          //  ce.Users.Create(use);
          //  ce.SaveChanges();
            //ce.Entry(use).State = System.Data.EntityState.Added;

        }

    }

I am unable to identify the issue. 我无法确定问题。

There are a number of things that could be causing this, some are covered in comments above: 造成这种情况的原因有很多,上面的注释中涉及了一些问题:

  • Trying to update a view 尝试更新视图
  • Trying to update a table that does not have a primary key 尝试更新没有主键的表
  • The primary key was added to the table directly, not via model first, the C# code therefore does not see the primary key 直接将主键添加到表中,而不是先通过模型添加,因此C#代码看不到主键
  • There is a reference to another table and there are some problems with the keys 有另一个表的引用,并且键存在一些问题

I would take a backup, delete what you have and then try again from scratch. 我将进行备份,删除您拥有的内容,然后从头开始重试。

PS: I just worked through the example in your link, it worked fine for me. PS:我只是通过您链接中的示例进行了工作,对我来说效果很好。

What I noticed was that the Add method was "AddObject" not "Add". 我注意到的是Add方法是“ AddObject”而不是“ Add”。 You should check the target framework for your project. 您应该检查项目的目标框架。

数据库表没有主键,在数据库中为用户表设置了主键。

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

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