2

我正在插入与现有父记录关联的子记录。如何刷新父记录以显示所有记录,包括新插入的子记录?

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-to-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);
}
4

1 回答 1

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);
}
于 2013-02-20T18:43:30.093 回答