我首先使用 EF 代码和延迟加载。
我的问题与如何有效地更新孙集合中的实体有关。首先,我担心这会在数据库中进行很多并不真正需要的调用。但是,如果我的域类不关心持久性,我看不出另一种方法来做到这一点。
这是课程:
public class Supplier
{
public int Id {get;set;}
//...Supplier properties
public virtual ICollection<Contract> Contracts {get;set;}
//supplier methods
}
public class Contract
{
public int id {get;set;}
public int SupplierId{get;set;}
//---Contract properties
[ForeignKey("SupplierId")]
public virtual Supplier Supplier {get;set;}
public virtual ICollection<DeliveryContract> DeliveryContracts {get;set;}
}
public class DeliveryContract
{
public int Id {get;set;}
public bool DeliveryOnMonday{get;set;}
public bool DeliveryOnTuesday{get;set}
//...30 different Delivery terms properties
public Department Department {get;set;}
public int ContractId {get;set;}
[ForeignKey("ContractId")
public virtual Contract Contract {get;set;}
}
供应商是聚合根。所以我有一个关于供应商的方法是 ChangeDeliveryContract,它对应于现实世界中会发生的事情。
public class Supplier
{
//properties
public void ChangeDeliveryContract (DeliveryContract cahangedDc)
{
//So from the supplier i have to find the contract to change
var dcToUpdate = Contracts
.SingleOrDefault(c=>c.Id == changedDc.ContractId)
.SingleOrDefalut(dc=>dc.Id == changedDc.Id);
//So... what do i do now? Map all 30 properties from changedDc to DcToUpdate
//Some business rules is also applied here i.e. there can only be one
// DeliveryContract between Supplier and Department
}
}
我使用 MVC,所以程序看起来像: public ActionResult Update (DeliveryContract changedDc, int supplierId)
{
var Supplier = supplierRepository.GetById(supplierid);
supplier ChangeDeliveryContract (changedDc);
supplierRepository.Save();
//More code...
}
首先,问题在于 ChangeDeliveryContract。我无法让它工作。另外,我觉得像我一样通过集合进行查询可能效率低下。第三,映射30+属性也感觉有点不对劲。
你们是怎么做的,这里有没有最佳实践。