实体框架db.SaveChanges期间建立新的数据行() [英] Entity Framework Creating new data rows during db.SaveChanges()

查看:140
本文介绍了实体框架db.SaveChanges期间建立新的数据行()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

创建AngularJS应用基于关闭此教程:的http://jphoward.word$p$pss.com/2013/01/04/end-to-end-web-app-in-under-an-hour/

类:

 公共类的Todo
{
    公众诠释ID {搞定;组; }
    公共虚拟状态状态{搞定;组; }
}公共类状态
{
    公众诠释ID {搞定;组; }
    公共字符串类型{搞定;组; }
}

功能就是你点击一个按钮,它改变了状态。当点击该按钮时,所有正确的事情被到Visual Studio中通过。它最初是没有更新的。经过一番研究,我发现了一些方法来强制更改,但随后在db.SaveChanges()加上一个新的行具有相同的类型,无论从任何最后一个是只是一个递增的ID状态。

JS调用更新:

  Api.Todo.update({ID:todoID},待办事项,函数(){
    $ location.path('/');
});

这此功能命中VS:

 私人的DataContext DB =新的DataContext();// PUT API /待办事项/ 5
HTT presponseMessage PutTodo(INT ID,待办事项待办事项)
{
    如果(!ModelState.IsValid)
    {
        返回Request.CreateErrorResponse(的HTTPStatus code.BadRequest,ModelState中);
    }    如果(ID!= todo.ID)
    {
        返回Request.CreateResponse(的HTTPStatus code.BadRequest);
    }    //发现,提到你需要检查已被跟踪的东西堆栈溢出
    VAR进入= db.Entry(待办事项);    如果(entry.State == EntityState.Detached)
    {
        VAR套= db.Set<&藤堂GT;();
        藤attachedEntity = set.Find(todo.ID); //你需要能够访问关键
        如果(attachedEntity!= NULL)
        {
            //下面的code不更新的外键的任何变化
            VAR attachedEntry = db.Entry(attachedEntity);
            attachedEntry.CurrentValues​​.SetValues​​(待办事项);
            db.Entry(attachedEntity).STATE = EntityState.Modified;            //当这个没有工作,我试着只是改变对已连接实体的地位
            //attachedEntity.Status = todo.Status;
            //db.SaveChanges();
            //但是当它击中的SaveChanges()就会在状态表中创建一个新的行。
        }
        其他
        {
            //这个code从来没有击中
            entry.State = EntityState.Modified; //这应该重视实体
        }
    }    尝试
    {
        db.SaveChanges();
    }
    赶上(DbUpdateConcurrencyException前)
    {
        返回Request.CreateErrorResponse(的HTTPStatus code.NotFound,前);
    }

我接近我的能力到底,并会喜欢一些帮助或指导。


解决方案

 公共类的Todo
{
    公众诠释ID {搞定;组; }    //外键
    公众诠释StatusID {搞定;组; } //< ====添加此行    公共虚拟状态状态{搞定;组; }
}

当您发布的数据更新外键的属性,而不是导航属性。

此外,检查:
为什么实体框架重新插入是否已有对象到我的数据库?
http://msdn.microsoft.com/en-us/magazine/dn166926.aspx

Creating an AngularJS application based off of this tutorial: http://jphoward.wordpress.com/2013/01/04/end-to-end-web-app-in-under-an-hour/

Classes:

public class Todo
{
    public int ID { get; set; }
    public virtual Status Status { get; set; }
}

public class Status
{
    public int ID { get; set; }
    public string Type { get; set; }
}

Functionality is that you click a button and it changes the status. When the button is clicked, all the right things are being passed in to Visual Studio. Originally it wasn't updating at all. After some research I found some ways to force the changes, but then at db.SaveChanges() it adds a new row to Status that has the same 'Type', just an incremented ID from whatever the last one is at.

JS that calls update:

Api.Todo.update({ id: todoID }, todo, function () {
    $location.path('/');
});

Which hits VS on this function:

private DataContext db = new DataContext();

// PUT api/Todo/5
HttpResponseMessage PutTodo(int id, Todo todo)
{
    if (!ModelState.IsValid)
    {
        return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
    }

    if (id != todo.ID)
    {
        return Request.CreateResponse(HttpStatusCode.BadRequest);
    }

    // Found a stack overflow that mentioned that you need to check for things already being tracked
    var entry = db.Entry(todo);

    if (entry.State == EntityState.Detached)
    {
        var set = db.Set<Todo>();
        Todo attachedEntity = set.Find(todo.ID);  // You need to have access to key
        if (attachedEntity != null)
        {
            // The following code does not update any changes to the foreign keys
            var attachedEntry = db.Entry(attachedEntity);
            attachedEntry.CurrentValues.SetValues(todo);
            db.Entry(attachedEntity).State = EntityState.Modified;

            // When this didn't work, I tried just changing the status on the already attached entity
            //attachedEntity.Status = todo.Status;
            //db.SaveChanges();
            // However when it hit SaveChanges() it created a new row in the Status table.
        }
        else
        {
            //This code was never hit
            entry.State = EntityState.Modified; // This should attach entity
        }
    }

    try
    {
        db.SaveChanges();
    }
    catch (DbUpdateConcurrencyException ex)
    {
        return Request.CreateErrorResponse(HttpStatusCode.NotFound, ex);
    }

I'm nearing the end of my capabilities and would love a little help or direction.

解决方案

public class Todo
{
    public int ID { get; set; }

    //Foreign key
    public int StatusID { get; set; } //<====Add this line

    public virtual Status Status { get; set; }
}

When you post your data update the foreign key property,not the navigational property

Also ,check this: Why Does Entity Framework Reinsert Existing Objects into My Database? http://msdn.microsoft.com/en-us/magazine/dn166926.aspx

这篇关于实体框架db.SaveChanges期间建立新的数据行()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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