在 n 层应用程序中,linq-to-sql 似乎没有明确的解决方案来更新具有子实体集的断开连接的实体。
我有一些 linq-to-sql 实体...
public partial class Location : INotifyPropertyChanging, INotifyPropertyChanged
{
public int id;
public System.Nullable<int> idLocation;
public string brandingName;
public System.Data.Linq.Binary timeStamp;
public EntitySet<LocationZipCode> LocationZipCodes;
}
public partial class LocationZipCode : INotifyPropertyChanging, INotifyPropertyChanged
{
public string zipcode;
public string state;
public int idLocationDetail;
public int id;
public System.Data.Linq.Binary timeStamp;
public EntityRef<Location> Location;
}
所以一个Location
实体会有一个EntitySet
of LocationZipCodes
。
域模型被映射到表示层使用Location
的视图模型,然后最终将更改后的视图模型实体发回,在该实体中它被映射回Location
域模型。从那里我更新实体并保存更改。这是处理程序:
public class ProgramZipCodeManagerHandler : IHttpHandler {
private LocationsZipCodeUnitOfWork _locationsZipCodeUnitOfWork = new LocationsZipCodeUnitOfWork();
public void ProcessRequest(HttpContext context) {
if (context.Request.HttpMethod == "POST") {
string json = Json.getFromInputStream(context.Request.InputStream);
if (!string.IsNullOrEmpty(json)) {
Location newLocation = Json.deserialize<Location>(json);
if (newLocation != null) {
//this maps the location view model from the client to the location domain model
var newDomainLocation = new Mapper<Location, DomainLocation>(new DomainLocationMapTemplate()).map(newLocation);
if (newDomainLocation.id == 0)
_locationsZipCodeUnitOfWork.locationRepository.insert(newDomainLocation);
else
_locationsZipCodeUnitOfWork.locationRepository.update(newDomainLocation);
_locationsZipCodeUnitOfWork.saveChanges(ConflictMode.ContinueOnConflict);
var viewModel = new Mapper<DomainLocation, Location>(new LocationMapTemplate()).map(newDomainLocation);
context.Response.ContentType = "application/json";
context.Response.Write(Json.serialize(viewModel);
}
}
}
}
}
这是我的更新方法locationRepository
:
protected System.Data.Linq.Table<T> _table;
public void update(T entity) {
_table.Attach(entity, true);
_context.Refresh(RefreshMode.KeepCurrentValues, entity);
}
public void update(T newEntity, T oldEntity) {
_table.Attach(newEntity, oldEntity);
_context.Refresh(RefreshMode.KeepCurrentValues, newEntity);
}
我可以看到与Location
实体直接关联的所有记录都在更新,但子集合 ( public EntitySet<LocationZipCode> LocationZipCodes
) 没有更新。
是否有一种明确的方法来更新具有也需要更新的子 EntitySet 的断开连接的实体?换句话说,我有一个分离的实体,它包含另一个实体的集合。该集合已更改,我需要在数据库中更新该集合。