我有以下方法。返回“无法执行更新查询”。如果我查询另一个实体属性,即“Order.Campaign.Id”,我是否需要包括一个连接?这会怎么样? ?
public void RemoveOrderItems(int companyId, int campaignId, int productId, int orderStatus)
{
using (ITransaction transaction = _session.BeginTransaction())
{
_session.CreateQuery("delete from OrderItem where Product.Id = '" + productId + "' and Order.Company.Id = '" + companyId + "' and Order.Campaign.Id = '" + campaignId + "' and Order.OrderStatus = '" + orderStatus + "'").ExecuteUpdate();
transaction.Commit();
}
}
**编辑**
这是sql语句。
DELETE oi
FROM OrderItems oi inner JOIN Orders o On oi.OrderId = o.Id
Where oi.ProductId = '13077' and o.CompanyId = '32' and o.CampaignId = '2' and o.OrderStatus = 3
答案 0 :(得分:3)
_session.CreateQuery(@"
delete OrderItem oi
where oi in
(select i
from OrderItem i
where i.Product.Id = :productId
and i.Order.Company.Id = :companyId
and i.Order.Campaign.Id :campaignId
and i.Order.OrderStatus = :orderStatus)
")
.SetParameter("productId", productId)
.SetParameter("companyId", companyId)
.SetParameter("campaignId", campaignId)
.SetParameter("orderStatus", orderStatus)
.ExecuteUpdate();
生成的SQL与完全完全与您手动创建的相同,但它在语义上是等效的。
答案 1 :(得分:1)
sql语句无效,where语句不正确。尝试在Microsoft SQL Server Management Studio中编写查询,然后使用params将其重写为CreateQuery。
答案 2 :(得分:1)
在SQL Server Management studio中找到正确的查询,并在执行类似我的示例之后(查询可以更加困难,当然还有join,subquery)
ISession session = SessionFactory.GetCurrentSession();
using (var tx = session.BeginTransaction())
{
try
{
IQuery myQuery = session.CreateQuery("DELETE FROM TableA c WHERE c.Field1 = :Filed1Value and c.Field2 = :Field2 ")
.SetParameter("Field1", 25)
.SetParameter("Field2", "Test")
myQuery.ExecuteUpdate();
tx.Commit();
}
catch (Exception)
{
tx.Rollback();
}
}