gpt4 book ai didi

c# - 如何使用 Entity Framework 更改另一个现有实体的相关实体

转载 作者:行者123 更新时间:2023-12-03 19:09:10 25 4
gpt4 key购买 nike

我有两个类(class):

public partial class ShipmentRoutePointDb
{
public long Id { get; set; } // Primary key
public System.Guid Uuid { get; set; }
public virtual TransportInfoDb NextTransportInfo { get; set; }
}

public partial class TransportInfoDb
{
public TransportInfoDb()
{
this.CertifiedConsignments = new HashSet<CertifiedConsignmentDb>();
this.TransportInfoGroups = new HashSet<TransportInfoGroupDb>();
}

public long Id { get; set; }

public string VehicleNumber { get; set; }

public virtual ICollection<CertifiedConsignmentDb> CertifiedConsignments { get; set; }
public virtual ICollection<TransportInfoGroupDb> TransportInfoGroups { get; set; }
}
我想更新 ShipmentRoutePointDb 的 VehicleNumber 以便检索更新记录:
var shipmentRoutePointDb = _shipmentRoutePointRepository.GetByUuid(updatedRoutePoint.Uuid);
然后我需要检查是否应该在 TransportInfoDb 中创建新记录,或者已经存在具有类似参数的记录:
var duplicate = transportInfoRepository.GetByParams(shipmentRoutePointDb.NextTransportInfo.VehicleNumber);
如果我能找到这样的记录,我会像这样更新shipmentRoutePointDb:
shipmentRoutePointDb.NextTransportInfo = duplicate;
shipmentRoutePointDb.NextTransportId = duplicate.Id;

_shipmentRoutePointRepository.Update2(shipmentRoutePointDb);

public void Update2(ShipmentRoutePointDb entity)
{
var entr = _context.Entry<ShipmentRoutePointDb>(entity);

entr.State = EntityState.Modified;

SaveChanges();
}
但是 SaveChanges() 抛出了一个异常:

System.InvalidOperationException: "A referential integrity constraintviolation occurred: The property value(s) of 'TransportInfoDb.Id' onone end of a relationship do not match the property value(s) of'ShipmentRoutePointDb.NextTransportId' on the other end."


我知道我没有在那里列出我使用的一些方法,但它们运行良好,它们的名称是不言自明的。

最佳答案

public void Update2(long transportId, long shipmentRouteId)
{
var shipment = _context.ShipmentRoutePointDb.FirstOrDefault(x => x.Id == shipmentRouteId);
_context.ShipmentRoutePointDb.Attach(shipment);

shipment.NextTransportId = transportId;

_context.ChangeTracker.DetectChanges();

SaveChanges();
}
这有帮助。主要原因是该项目禁用了检测更改。

关于c# - 如何使用 Entity Framework 更改另一个现有实体的相关实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62789715/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com