在Linq中删除查询

uidvcgyl  于 2022-12-06  发布在  其他
关注(0)|答案(8)|浏览(135)

我有这个简单的代码,但它显示错误。我不知道我哪里出错了。它显示错误在最后一行。

linq_testDataContext db = new linq_testDataContext();
 var remove = from aremove in db.logins
         where aremove.username == userNameString && aremove.Password == pwdString
         select aremove;
 db.logins.DeleteOnSubmit(remove);
wljmcqd8

wljmcqd81#

DeleteOnSubmit接受单一对象。您传递的是IEnumerable<login>。请改用DeleteAllOnSubmit,或从结果集合中选取单一对象,如下所示:

var remove = (from aremove in db.logins 
             where aremove.username == userNameString 
                && aremove.Password == pwdString 
             select aremove).FirstOrDefault(); 

if(remove != null)
{
    db.logins.DeleteOnSubmit(remove);
}
des4xlb0

des4xlb02#

缺少用于删除所有实体foreach循环
使用方法如下

var remove = from aremove in db.logins
     where aremove.username == userNameString && aremove.Password == pwdString
     select aremove;

之后

foreach (var detail in remove)
{
    db.logins.DeleteOnSubmit(detail);
}

最后

try
{
    db.SubmitChanges();
}
catch (Exception e)
{
    // Provide for exceptions.
}

希望这对你有帮助。

628mspwn

628mspwn3#

代替:

db.logins.DeleteOnSubmit(remove);

调用DeleteAllOnSubmit(),如下所示:

db.logins.DeleteAllOnSubmit(remove.ToList());

确保之后调用db.SubmitChanges()。您也可以使用.AsEnumerable(),或者。但是,如果这是一个大的删除操作,在这种情况下,您可能需要考虑绕过LINQ。

kkbh8khc

kkbh8khc4#

使用此代码其工作

var remove = (from aremove in db.logins 
             where aremove.username == userNameString 
                && aremove.Password == pwdString 
             select aremove).FirstOrDefault(); 

if(remove != null)
{
     db.logins.Remove(remove);
     db.SaveChanges();
}
yfwxisqw

yfwxisqw5#

尝试使用方法first(),类似于:

var remove = 
    (from aremove in db.logins where aremove.username == userNameString 
    && aremove.Password == pwdString select aremove).first();

db.logins.DeleteOnSubmit(remove);
mrwjdhj3

mrwjdhj36#

良好实践

private void DeleteCourse()
        {
            int id = Convert.ToInt32( txtSearch.Text);
            CourseDemoDataContext cdContext = new CourseDemoDataContext();
            course courseobj = cdContext.courses.Single(courses => courses.COURSE_ID == id);
            cdContext.courses.DeleteOnSubmit(courseobj);
            cdContext.SubmitChanges();
        }
rfbsl7qr

rfbsl7qr7#

你可以试试这个,它会为你工作。

linq_testDataContext _DbContext = new linq_testDataContext();
var remove = _DbContext.aremove.where(x=>x.username == userNameString && x.Password == pwdString).FirstOrDefault();
if(remove != null)
{
     db.logins.Remove(remove);
     db.SaveChanges();
}
2o7dmzc5

2o7dmzc58#

我认为这可以通过使用代码的where()和Tolist()来实现......考虑到db.logins是一个数据表,remove表示表中的数据行,username、Password表示要检查的列...... linq可以这样写......

db.logins.AsEnumerable()
               .Where(aremove  => aremove["username"].ToString() == "userNameString" && aremove["Password"].ToString() == "pwdString")
               .ToList()
               .ForEach(m => m.Delete());

相关问题