在EF中删除记录时如何返回删除的记录列?

时间:2016-05-10 16:48:53

标签: c# entity-framework-6

我正致力于减少托管存储过程,并且发现这不知道如何(或者如果)将其成功移植到Entity Framework:

-- select out filename so the caller can delete the file from the filesystem
SELECT  SystemFileName
FROM    File
WHERE   FileId = @fileId

-- now delete
DELETE
FROM    File
WHERE   FileId = @fileId

基本上,proc获取一个id,返回它将删除的记录的文件名,然后删除该行。然后,调用代码具有文件名,以执行任何文件系统清除,从而减少孤立文件的可能性。

现在使用Entity Framwork,我可以找到所有文件并执行删除,但如果我在循环中这样做,那将非常低效。

我可以尝试记录我的尝试,但它比任何可编译的伪代码更多。

3 个答案:

答案 0 :(得分:1)

假设您有少于4000条记录要删除原因

1)选择要删除的ID和文件名 2)将这些结果存储在数组/列表中 3)使用IN子句删除所有记录

// get all of the records to be deleted
var records = context.Files.Where(x => x.Name.Contains("delete-me")).Select(x => new {x.Id, x.Name}).ToList();

// mark all of our files to be deleted
context.Files.RemoveAll(x => records.Contains(x.Id)); // not sure if this line is correct as I am writing this in notepad, but it will give you a good enough idea

// execute our save, which will delete our records
context.Save();

// return the list of records that have been deleted back to the caller
return records;

答案 1 :(得分:1)

Sheet1

答案 2 :(得分:0)

说实话,我认为这是一个批量操作,而不是EF(或其他ORM)的理想选择。我不确定哪个更重要,简化查询或使用EF。但是,如果您想简化查询,可以执行类似的操作并同时读取受影响的已删除值

DELETE
OUTPUT deleted.SystemFileName -- or OUTPUT deleted.*
FROM    File
WHERE   FileId = @fileId