简体   繁体   English

实体框架SaveChanges不起作用

[英]Entity Framework SaveChanges does not work

I have this piece of code but it does not work, and I do not see where id the problem. 我有这段代码,但是它不起作用,并且我看不到问题所在的位置。

No exception is caught. 没有异常被捕获。

I'm working with Entity Framework 4. The SaveChanges call does not seem do anything in the database. 我与实体框架4.工作SaveChanges调用似乎并没有做数据库中的任何东西。

try
{
    Demande_Rage_Animale editdemande = DemandeRageAnimaleDAO.First(s => s.ID == demandebean.ID);

    //frombeanTodemande(demandebean, editdemande);
    editdemande.num_rapport = "111111";

    //editdemande.EntityState.
    DemandeRageAnimaleDAO.SaveChanges();
}
catch (Exception ex)
{
    Logger.Error("==> Modifier_demande_RageAnimale : " + ex.InnerException);
}

You must mark the entity as modified before calling SaveChanges: 您必须在调用SaveChanges之前将实体标记为已修改:

DemandeRageAnimaleDAO.Entry(editdemande).State = EntityState.Modified;
DemandeRageAnimaleDAO.SaveChanges();

In older versions of Entity Framework you can use this: 在较旧版本的Entity Framework中,您可以使用以下命令:

DemandeRageAnimaleDAO.ObjectStateManager.ChangeObjectState(editdemande, System.Data.EntityState.Modified);

It's possible that the method shown in the question is not the full picture and perhaps the entity has become detached. 问题中显示的方法可能不完整,并且实体可能已分离。 In this case you can attach it back to the context, mark it as modified and call SaveChanges: 在这种情况下,您可以将其附加到上下文,将其标记为已修改并调用SaveChanges:

var editdemande = DemandeRageAnimaleDAO.First(s => s.ID == demandebean.ID);

// whatever happens here?

DemandeRageAnimaleDAO.Demande_Rage_Animale.Attach(editdemande);
editdemande.num_rapport = "111111";
DemandeRageAnimaleDAO.ObjectStateManager.ChangeObjectState(editdemande, System.Data.EntityState.Modified);
DemandeRageAnimaleDAO.SaveChanges();

The object context must know the state of an object to save changes back to the data source.ObjectStateEntry objects store EntityState information. 对象上下文必须知道对象的状态才能将更改保存回数据源。ObjectStateEntry对象存储EntityState信息。 The SaveChanges methods of the ObjectContext process entities that are attached to the context and update the data source depending on the EntityState of each object. ObjectContext的SaveChanges方法处理连接到上下文的实体,并根据每个对象的EntityState更新数据源。 For more information, see Creating, Adding, Modifying, and Deleting Objects. 有关更多信息,请参见创建,添加,修改和删除对象。

In your case using EF 4.0 you need call this 在使用EF 4.0的情况下,您需要调用此

_yourContext.ObjectStateManager.ChangeObjectState(editdemande, System.Data.EntityState.Modified);

with version 4.1 its done like 与版本4.1一样完成

_yourContext.Entry(editdemande).State = System.Data.EntityState.Modified;

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

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