将linq中包含子实体的断开连接的实体更新为sql

时间:2013-03-19 15:35:48

标签: c# linq-to-sql

在n层应用程序中,linq-to-sql似乎没有明确的解决方案来更新具有子EntitySets的断开连接的实体。

我有一些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 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)没有更新。

是否有明确的方法来更新具有子实体集的断开连接的实体,该实体也需要更新?换句话说,我有一个具有另一个实体集合的分离实体。该集合已更改,我需要在数据库中更新它。

2 个答案:

答案 0 :(得分:2)

不......你做不到。

根据您使用的对象附加和分离对象,不会影响相关对象(实体)。

您可以从这里阅读更多信息:
Attaching and Detaching Objects

考虑一种情况,其中对象A与集合B相关,该集合B填充有1000个值。 您分离A并将其发送到某个远程处理 - A在B关系中以null发送..现在A被带回到您的程序 - 无法知道AB null是远程处理的结果或者是它已经为null提供了远程处理。

在使用此答案发布的链接中 - 请向下滚动以仔细阅读标题为:
的部分  分离对象的注意事项。

答案 1 :(得分:0)

我不太清楚我理解你的问题,但是这里......像下面的实体对象扩展,或许你将实体重新连接到上下文等,将通过将实体重新附加到对象上下文并适当地设置entitystate来工作。 / p>

    /// <summary>
    /// AttachEntityToObjectContext attaches an EntityObject to an ObjectContext
    /// </summary>
    /// <param name="entityWithRelationships">An EntityObject that has relationships</param>
    /// <param name="newContext">The ObjectContext to attach the entity to</param>
    /// <returns>True if the entity has relationships (and therefore the method could succeed). Otherwise false.</returns>
    /// <remarks>Objects are retrieved using one ObjectContext, stored in ViewState and then
    /// an attempt to save them is then made. The save attempt does not save the object. This is because it is a different context which is saving the object.
    /// So the object needs to be detached from its old context, added to the new context and have its EntityState maintained so that it gets saved.</remarks>
    public static bool AttachEntityToObjectContext(this IEntityWithRelationships entityWithRelationships, ObjectContext newContext)
    {
        EntityObject entity = entityWithRelationships as EntityObject;
        if (entity == null)
        {
            return false;
        }

        if (entity.EntityState != EntityState.Detached)
        {
            ObjectContext oldContext = entity.GetContext();
            if (oldContext == null)
            {
                return false;
            }

            if (oldContext != newContext)
            {
                EntityState oldEntityState = entity.EntityState;
                oldContext.Detach(entity);
                newContext.Attach(entity);
                newContext.ObjectStateManager.ChangeObjectState(entity, oldEntityState);
            }
        }

        return true;
    }

    /// <summary>
    /// GetContext gets the ObjectContext currently associated with an entity
    /// </summary>
    /// <param name="entity">An EntityObject</param>
    /// <returns>The ObjectContext which the entity is currently attached to</returns>
    private static ObjectContext GetContext(this IEntityWithRelationships entity)
    {
        if (entity == null)
        {
            throw new ArgumentNullException("entity");
        }

        var relationshipManager = entity.RelationshipManager;

        var relatedEnd = relationshipManager.GetAllRelatedEnds().FirstOrDefault();

        if (relatedEnd == null)
        {
            // No relationships found
            return null;
        }

        var query = relatedEnd.CreateSourceQuery() as ObjectQuery;

        if (query == null)
        {
            // The Entity is Detached
            return null;
        }

        return query.Context;
    }