使用 context.remove(class) 删除数据库中的条目 win universal app c#

Deleting entry in database using context.remove(class) win universal app c#

我尝试使用 fromwhere 使用 sql 类型的命令从数据库中删除一个条目,并且在执行 db.SaveChanges() 后成功了。我已经看到其他示例使用新创建的 Person np = new Person() { Name: "sample"}; 并将其作为参数传递给 db.Remove(np) 但我发现了这个错误

error Database operation expected to affect 1 row(s) but actually affected 0
row(s). Data may have been modified or deleted since entities were loaded.

这是工作代码

Person mm = (from pp in db.People where pp.Name == "sample" select pp)
              .FirstOrDefault();
db.People.Remove(mm);

然而这不是

var m = new Person() { Name = "sample" };
db.Remove(m);

有人能赐教吗?谢谢。

您正试图在不提供 ID 的情况下删除记录。没有 ID 的记录无法删除。

第一种情况有效,因为您 select 来自数据库的人。所以 Person 对象包含 (或应该包含) 一个 Id.

第二段代码只是创建了一个新的 Person 而没有将其插入到数据库中。

    var id = (from pp in db.People where pp.Name == "sample" select pp).FirstOrDefault().Id; //Get id from person with name "sample"
    var m = new Person() {Id = id};
    db.People.Remove(m);

如果你想使用DbContext.Remove方法删除一个条目,你应该可以为Person设置ID。

如果我们获取 ID 并将其设置为 Person 并调用 DbContext.Remove,它将抛出 System.InvalidOperationException:

'The instance of entity type 'Person' cannot be tracked because another instance of this type with the same key is already being tracked. When adding new entities, for most key types a unique temporary key value will be created if no key is set (i.e. if the key property is assigned the default value for its type). If you are explicitly setting key values for new entities, ensure they do not collide with existing entities or temporary values generated for other new entities. When attaching existing entities, ensure that only one entity instance with a given key value is attached to the context.'

如果当前的DbContext被释放,我们可以使用DbContext.Remove方法创建新的DbContext。如果知道 Person 的 ID,可以使用 DbContext.Remove 方法。如果没有,不推荐。

以下代码有效:

int myId;
using (var db = new BloggingContext())
{
    var id = (from pp in db.People where pp.Name == "sample" select pp).FirstOrDefault().PersonId;
    myId = id;
}       
using (var db = new BloggingContext())
{
    var person = new Person() { PersonId = myId};
    db.Remove(person);
    db.SaveChanges();
}