简体   繁体   English

使用实体框架删除记录时出错

[英]Error when remove record using Entity Framework

I'm trying to remove record from database using Entity Framework, but I get the following error:我正在尝试使用实体框架从数据库中删除记录,但出现以下错误:

System.InvalidOperationException: 'Attaching an entity of type 'PayRoll_v1.database.Administration' failed because another entity of the same type already has the same primary key value. System.InvalidOperationException:“附加类型为“PayRoll_v1.database.Administration”的实体失败,因为同一类型的另一个实体已经具有相同的主键值。 This can happen when using the 'Attach' method or setting the state of an entity to 'Unchanged' or 'Modified' if any entities in the graph have conflicting key values.如果图中的任何实体具有冲突的键值,则在使用“附加”方法或将实体的 state 设置为“未更改”或“已修改”时,可能会发生这种情况。 This may be because some entities are new and have not yet received database-generated key values.这可能是因为某些实体是新实体,尚未收到数据库生成的键值。 In this case use the 'Add' method or the 'Added' entity state to track the graph and then set the state of non-new entities to 'Unchanged' or 'Modified' as appropriate.'在这种情况下,使用“添加”方法或“添加”实体 state 来跟踪图形,然后将非新实体的 state 酌情设置为“未更改”或“已修改”。

This is the relevant code part:这是相关的代码部分:

    var genderCodeAsInt = Convert.ToInt32(txtCode.Text);

    var C = new database.Administration
    {
        Code = genderCodeAsInt,
    };

    db.Administrations.Attach(C);
    db.Administrations.Remove(C);
    db.SaveChanges();

You can set the attached entry's state to Deleted :您可以将附加条目的 state 设置为Deleted

db.Administrations.Entry(C).State = EntityState.Deleted;
db.Administrations.SaveChanges();

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

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