C# EF6更新时出现InvalidOperationException,但在手动更改数据库后仍有效

C# EF6更新时出现InvalidOperationException,但在手动更改数据库后仍有效,c#,entity-framework,entity-framework-6,C#,Entity Framework,Entity Framework 6,我正在尝试更新实体的FK。我是这样做的: myEntity.FK_ID= Guid.Parse("aff4b5d9-e197-4f0d-85ff-b04464d9e4f0"); //Entity with this Guid exists inside the DB myEntity.ForeignKeyProperty= null; using (MyContext db = new MyContext ()) { //db.Benutzer.Attach(entity); // &

我正在尝试更新实体的FK。我是这样做的:

myEntity.FK_ID= Guid.Parse("aff4b5d9-e197-4f0d-85ff-b04464d9e4f0"); //Entity with this Guid exists inside the DB
myEntity.ForeignKeyProperty= null;
using (MyContext db = new MyContext ())
{
    //db.Benutzer.Attach(entity); // <-- Same Exception
    db.Entry(entity).State = EntityState.Modified;
}
然后我尝试更新实体(新上下文),如下所示:

myEntity.FK_ID= Guid.Parse("aff4b5d9-e197-4f0d-85ff-b04464d9e4f0"); //Entity with this Guid exists inside the DB
myEntity.ForeignKeyProperty= null;
using (MyContext db = new MyContext ())
{
    //db.Benutzer.Attach(entity); // <-- Same Exception
    db.Entry(entity).State = EntityState.Modified;
}
我真的不知道为什么。然后我尝试了以下方法: 我在数据库中将FK_ID的值更改为目标值。这起作用了(好吧,可能会有一些东西…) 但后来我把这个值换成了其他值,它仍然有效

在手动更改数据库之后,它现在每次都适用于这个实体。如果我尝试更新另一个实体,我会得到相同的异常。你知道为什么会这样吗

问候,, 马塞尔

编辑: 下面是一个更完整的代码:

    //In MVC-Controller
Benutzer dbBenutzer = Database.GetBenutzerByID(model.ID_Benutzer);

// ... Do some other changes to the entity

dbBenutzer.ChangeMitarbeiter = null;
dbBenutzer.MitarbeiterChange_ID = CurrentUser.Mitarbeiter_ID;

//...SaveChanges via 
Database.Update<Benutzer>(dbBenutzer);

// In Repository
public static int Update<E>(E entity) where E : class
{
    using (Context db = new MMVContext())
    {
        try
        {
            db.Entry(entity).State = EntityState.Modified;  //EXCEPTION                      
            return SaveRepositoryChanges<E>(db);
        }
        catch (Exception e)
        {
            Logging.Error(e.ToExtString());
            return -1;
        }
    }
}      
//在MVC控制器中
Benutzer dbBenutzer=Database.GetBenutzerByID(model.ID\u Benutzer);
// ... 对实体进行其他一些更改
dbBenutzer.ChangeMitarbeiter=null;
dbBenutzer.MitarbeiterChange_ID=CurrentUser.Mitarbeiter_ID;
//…通过保存更改
数据库更新(dbBenutzer);
//存储库中
公共静态int更新(E实体),其中E:class
{
使用(Context db=new MMVContext())
{
尝试
{
db.Entry(entity.State=EntityState.Modified;//异常
返回SaveRepositoryChanges(db);
}
捕获(例外e)
{
Logging.Error(例如ToExtString());
返回-1;
}
}
}      

您试图在另一个表上分配的FK是否为?我的意思是,是否还有另一个实体具有FK aff4b5d9-e197-4f0d-85ff-b04464d9e4f0?是的,表中存在Guid。。。我试图分配给exist的所有数据都显示了代码的其余部分,一部分是myEntity,另一部分是entity。您是如何使用它的,它是在哪里创建的?为什么不分配值呢?您尝试分配具有该FK的对象,然后更新上下文?你试过了吗?我添加了一个更完整的代码示例。我试图向NavigationProperty添加一个实体,但结果是相同的=>异常。即使同时设置(实体和FK)也会导致异常。