我有以下物體:
public class Device
{
public long Guid { get; set; }
public List<Computer> Computers { get; set; }
public string ShopName { get; set; }
}
public class Computer
{
public long Guid { get; set; }
public long SerialNo { get; set; }
public Device Device { get; set; }
public Condition Condition { get; set; }
}
public class Condition
{
public long Guid { get; set; }
public bool hasDamage { get; set; }
public bool IsSecondHand { get; set; }
public Computer Computer { get; set; }
}
我的服務要求是:
public class Request
{
public long? DeviceGuid {get; set;}
public long? SerialNo {get; set;}
public bool? IsSecondHand {get; set;}
}
我想根據要求更新所有計算機
foreach (var requestItem in RequestList)
{
var ComputerPredicate = PredicateBuilder.True<Computer>()
.And(x => x.SerialNo== requestItem.SerialNo)
.And(x => x.Device.Guid== requestItem.DeviceGuid);
var computers = from computers in ISession.Query<Computer>()
.Where(ComputerPredicate)
select computers;
computers.Update(u => new Computer()
{
Condition = new Condition()
{
IsSecondHand = requestItem.IsSecondHand.GetValueOrDefault(false),
}
});
如果Request.DeviceGuid不為空,則更新屬于該設備的所有計算機;如果Request.SerialNo不為空,我只更新計算機。其中一個在串列的每個專案中始終為空。
但我收到一個錯誤
NHibernate.Exceptions.GenericADOException: '無法執行更新查詢[SQL: 更新計算機設定條件.IsSecondHand=? where and serialno=?]'
PostgresException: 42703: 關系“計算機”的列“條件”不存在
SQL中確實沒有關系。
還有另一個選項可以成功更新,但我不確定這是一種有效的方法:
var computerList = computers.ToList();
foreach (var computer in computerList)
{
computer.Condition.IsSecondHand = requestItem.IsSecondHand.GetValueOrDefault(false);
ISession.Save(computer)
}
那么我怎樣才能以最有效的方式處理這種情況呢?
uj5u.com熱心網友回復:
NHibernate 中的 LINQ 更新不支持對關系物體的更新。您可以嘗試使用子查詢來查找您需要更新的所有物體。就像是:
var entitiesToUpdateSubQuery = session.Query<Computer>()
.Where(ComputerPredicate)
.Select(x => x.Condition); //<- Select entity you need to update
session.Query<Condition>() //<- Write update query directly on entity you need to update
.Where(c => entitiesToUpdateSubQuery.Contains(c))
.Update(c =>
new Condition()
{
IsSecondHand = requestItem.IsSecondHand.GetValueOrDefault(false),
}
);
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/427137.html
標籤:C# 林克 休眠 可查询的 linq-to-nhibernate
上一篇:如何在LINQ中撰寫for回圈
下一篇:LINQ比較時間跨度
