2013-02-19 93 views
2

我插入與現有父記錄關聯的子記錄。我如何刷新父記錄以顯示所有內容,包括新插入的子記錄?將子記錄插入linq到sql後刷新實體

context.Refresh(RefreshMode.OverwriteCurrentValues, entity)不起作用。我嘗試

一個更完整的例子:

Location newLocation = Json.deserialize<Location>(json); 
if (newLocation != null) { 
    IEnumerable<string> zipCodes = Regex.Split(newLocation.zipCodes, @"[\s,;]+"); 

    // this verifies the new zipcodes against a table of all US zipcodes and returns matches 
    var newLocationZipCodes = _zipCodeRepository.match(zipCodes).Select(item => new LocationZipCode { idLocation = newLocation.id, state = item.state, zipcode = item.zipcode }); 

    // get the parent entity 
    var domainLocation = _unitOfWork.locationRepository.getFirst(l => l.id == newLocation.id); 

    // insert child entities 
    if (newLocationZipCodes.Any()) { 
     _unitOfWork.locationZipCodeRepository.insertAll(newLocationZipCodes); 
     _unitOfWork.saveChanges(ConflictMode.ContinueOnConflict); 
    } 

    // this isn't working 
    _unitOfWork.refresh(RefreshMode.OverwriteCurrentValues, domainLocation); 
    return domainLocation; 
} 

下面是LINQ到SQL創建LocationZipCode類的基本表示:

public class LocationZipCode { 
    int idLocation; 
    string zipcode; 
    string state 
    EntityRef<Location> location; 
} 

這裏是我的刷新方法我的UnitOfWork:

public void refresh(RefreshMode refreshMode, object entity) { 
    _context.Refresh(refreshMode, entity); 
} 

回答

1

而不是刷新上下文我改變了我插入我的方式子記錄到數據庫中。因此,而不是...

_unitOfWork.locationZipCodeRepository.insertAll(newLocationZipCodes); 

我這樣做...

domainLocation.LocationZipCodes.AddRange(newLocationZipCodes); 

所以更新的代碼看起來是這樣的...

Location newLocation = Json.deserialize<Location>(json); 
if (newLocation != null) { 
    IEnumerable<string> zipCodes = Regex.Split(newLocation.zipCodes, @"[\s,;]+"); 

    var newLocationZipCodes = _zipCodeRepository.match(zipCodes).Select(item => new LocationZipCode { idLocation = newLocation.id, state = item.state, zipcode = item.zipcode }); 
    var domainLocation = _unitOfWork..locationRepository.getFirst(l => l.id == newLocation.id); 

    if (newLocationZipCodes.Any()) { 
     domainLocation.LocationZipCodes.AddRange(newLocationZipCodes); 
     _unitOfWork.saveChanges(ConflictMode.ContinueOnConflict); 
    } 

    return new Mapper<DomainLocation, Location>(new LocationMapTemplate()).map(domainLocation); 
}