【问题标题】:How to delete in Entity Framework如何在实体框架中删除
【发布时间】:2015-07-16 08:09:36
【问题描述】:

我有一个问题:

var q = (from c in session.db.students
          where c.id==5
          select c);

如何删除这条记录?我试过deleteonsubmitdeleteobjectdelete...但没有一个是未知的。
例如在下面的代码中,删除未知:

foreach (student s in q)
{ s.deleteobject;}
session.db.savechanges();

或:

var q = (from c in session.db.students
          where c.id==5
          select c).deleteOnSubmit();

没有一个没有定义....问题出在哪里?

【问题讨论】:

  • 为什么将 DBContext 存储在 session 中?你试过db.students.remove(s);
  • @EmmanuelM。我使用 remove 但我看到此错误:错误 1 ​​'System.Data.Entity.DbSet.Remove(WindowsFormsApplication1.PurchUtility)' 的最佳重载方法匹配有一些无效参数
  • 你能告诉我们使用.Remove失败的代码吗?看起来你没有使用正确的上下文成员或实体类型
  • @EmmanuelM。 IEnumerable w = (from s in Session.DB.Sponsers where s.Id == 1 select s); foreach(赞助商 v in w){ Session.DB.Sponsers.Remove(w); //这一行是错误的 }
  • 什么是Session.DB?如果是你自己的类型,Remove 方法里面是什么?如果没有这些相关信息,我们将无能为力。

标签: c# entity-framework


【解决方案1】:

您想在 DbContext 对象上调用 .remove([record])。使用您的代码,您将执行以下操作:

var q = (from c in session.db.students where c.id == 5 select c);

foreach (student s in q)
{
    session.db.Remove(s);
}
session.db.SaveChanges();

或使用基于方法的查询(删除 id 为 5 的单个记录):

var s = session.db.students.Where(p => p.id == 5).FirstOrDefault();
if(s != null) { session.db.Remove(s); }
session.db.SaveChanges();

【讨论】:

  • 但我也没有 Remove :( IEnumerable w = (from s in Session.DB.Sponsers where s.Id == 1 select s); foreach(Sponser v in w) { Session.DB.Sponsers.Remove(w); //这一行是错误的 }
【解决方案2】:

你应该使用Remove:

var q = (from c in session.db.students
          where c.id==5
          select c);

foreach(student s in q)
{
    session.db.students.Remove(s);
}

session.db.SaveChanges();

【讨论】:

  • 我在行中看到此错误: session.db.students.remove(s) :错误 1 ​​'System.Data.Entity.DbSet.Remove( WindowsFormsApplication1.PurchUtility)' 有一些无效参数
【解决方案3】:

看看这个答案。也许会有所帮助

https://stackoverflow.com/a/17723658/4571664

那么你也可以使用这个

 ((DbContext)dbContext).Set<objectName>().Remove(singleObject);
 dbContext.SaveChanges();

如果需要删除多个对象,可以在foreach中使用这段代码。

【讨论】:

    【解决方案4】:

    尝试使用dbcontext,可以使用remove或removerange。

    using (var MyContext= new CRMDBContext(connString))
                    {
                        MyContext.[Table].RemoveRange(MyContext.[Table].Where(x => x.[column]== [column]));
                        MyContext.SaveChanges();
                    }
    

    【讨论】:

    • no... 问题尚未解决,我想从查询中删除。不在范围内
    【解决方案5】:

    您可以在上下文中使用 Remove() 或 RemoveRange() 方法来删​​除对象。

    如果您有对象集合:

    session.db.students.RemoveRange(collectionOfStudents);
    session.db.SaveChanges();
    

    如果您只有一个对象:

    session.db.students.Remove(oneStudent);
    session.db.SaveChanges();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-24
      • 1970-01-01
      • 2011-08-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多