在n層應用程序中,linq-to-sql似乎沒有明確的解決方案來更新具有子EntitySets的斷開連接的實體。更新在linq中有子實體的斷開連接的實體到sql
我有一些LINQ到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
實體將有LocationZipCodes
的EntitySet
。
的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
)相關的所有記錄是沒有被更新。
是否有一個明確的方法來更新一個斷開的實體,該實體的子實體集也需要更新?換句話說,我有一個擁有另一個實體集合的分離實體。該集合已更改,我需要在數據庫中更新它。
子集合中的條目是否有其各自的ID? – rhughes 2013-03-22 12:40:46
是的,他們有他們的編號 – bflemi3 2013-03-22 12:48:04