我正在尝试使用LINQ执行DELETE,这将生成一个查询。
以下是我的表现:
// NorthwintEntities is an ADO.NET Entitity Data Model
var northwindEntities = new NorthwindEntities();
northwindEntities.Order_Details.Delete(o => o.Order_ID == 11076);
这是我的扩展名:
public static class EntityExtensions
{
private static Regex rxTableName = new Regex(@"^FROM\s+(?<table>\[[^\]]*\](\.\[[^\]]*\]){0,2})\s+AS\s+(?<alias>\[[^\]]*\])", RegexOptions.Multiline);
public static void Delete<T>(this ObjectSet<T> entity, Expression<Func<T, bool>> expression) where T : EntityObject
{
var selectQuery = entity.Where(expression).Select(x => 1);
string selectQueryString = ((ObjectQuery)selectQuery).ToTraceString();
string deleteQueryString = ConvertSqlSelectToDelete(selectQueryString);
entity.Context.ExecuteStoreCommand(deleteQueryString);
}
private static string ConvertSqlSelectToDelete(string selectQuery)
{
if (selectQuery.IndexOf(" JOIN ") > -1)
{
throw new Exception("Query with JOIN is not supported: " + selectQuery);
}
Match match = rxTableName.Match(selectQuery);
if (!match.Success)
{
throw new Exception("Unable to convert SELECT: " + selectQuery);
}
string deleteQuery = "DELETE \r\n" + selectQuery.Substring(match.Index);
deleteQuery = deleteQuery.Replace(match.Groups["alias"].Value + ".", "");
deleteQuery = deleteQuery.Replace("AS " + match.Groups["alias"].Value, "");
return deleteQuery;
}
}
这有效,但我有一些意见。
所以我的问题是:有更简单的方法吗?如果是这样,它是什么?
任何帮助都将受到赞赏。
答案 0 :(得分:8)
安装实体框架扩展库 (PM&gt; Install-Package EntityFramework.Extended)
在代码中导入EntityFramework.Extensions
删除内部查询
指定的记录context.Orders.Where(o=>o.User_ID == 1).Delete();
删除订单中包含userID = 1
的所有记录答案 1 :(得分:5)
批量删除的一种方法是在外键上设置ON CASCADE DELETE。您需要在设计器中的关系上设置CASCADE,并在数据库中的关系上设置ON CASCADE DELETE。
要从订单EF中删除产品导航属性,将(产品属性数)+1语句删除到数据库。
我更喜欢这样做:
var order = context.Orders.Include(p=>p.Products).Where(o=>o.Order_ID == 11076);
foreach(Product product in order.Products.ToList())
{
context.Entry(product).State = EntityState.Deleted;
}
context.Entry(order ).State = EntityState.Deleted;
context.SaveChanges();
希望它有所帮助。