2

如果我有一张这样的桌子:

StudentId  | ... | SchoolId
___________|_____|__________ 
1          | ... | SchoolA
2          | ... | SchoolA
3          | ... | SchoolB
...

我想删除从 schoolA 到 schoolZ 的学校列表(使用 LINQ-to-SQL):

foreach(School s in schools){
    db.Schools.DeleteOnSubmit(s);
    db.submitChanges();
}

SchoolA并且SchoolB会因为上面的 FK 引用而失败

如何继续并删除所有其他学校,丢弃发生异常的学校?

4

5 回答 5

6

仅包括没有学生的学校:

var schoolsToDelete = schools.Where(x => !x.Students.Any());
db.Schools.DeleteAllOnSubmit(schoolsToDelete); 
db.submitChanges();
于 2011-08-30T14:51:50.037 回答
1

默认情况下,LINQ to SQL 在第一个错误时失败并回滚事务。如果您希望它继续处理它可以做的任何事情,您可以在 SubmitChanges 上传递 ConflictMode 重载以允许它继续运行。以下来自“LINQ in Action”的示例尝试发出所有排队的更新,然后输出通过处理 ChangeConflictException 遇到的冲突。

try
{
    context.SubmitChanges(ConflictMode.ContinueOnConflict);
}
catch (ChangeConflictException)
{
    var exceptionDetail = 
        from conflict in context.ChangeConflicts
        from member in conflict.MemberConflicts
        select new
        {
            TableName = GetTableName(context, conflict.Object),
            MemberName = member.Member.Name,
            CurrentValue = member.CurrentValue.ToString(),
            DatabaseValue = member.DatabaseValue.ToString(),
            OriginalValue = member.OriginalValue.ToString()
        };
    exceptionDetail.Dump();
}

自然,积极主动地尝试删除 Mark Cidade 所证明的有效记录当然要好得多。

于 2011-08-30T15:13:53.873 回答
0

I agree with Mark's solution. If you wan't to delete the school and its students, you can use:

foreach (School s in schools)
{
    db.Students.DeleteAllOnSubmit(s.Students);
    db.Schools.DeleteOnSubmit(s);
}

db.submitChanges();

That way you are fulfilling the FK constraint, so no errors are thrown.

于 2011-08-31T09:48:56.853 回答
0

我同意 Mark Cidade 的观点,但我可以建议改进使用连接范围向数据库服务器发送单个请求。

于 2011-08-30T16:22:37.253 回答
-1

找到了一个简单的方法

foreach(School s in schools){

    try{
        db.Schools.DeleteOnSubmit(s);

        db.submitChanges();
    }
    catch(SqlException exp){
        if(exp.Message.Contains("The DELETE statement conflicted with the REFERENCE constraint"))   //just checking if is FK reference
            db.Schools.InsertOnSubmit(s);   //=)
        else
            throw;

    }
}
于 2011-08-31T09:34:43.003 回答