在linq中插入子记录到sql后刷新实体

时间:2013-02-19 14:49:54

标签: c# linq-to-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-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);
}

1 个答案:

答案 0 :(得分: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);
}