English 中文(简体)
实体框架告诉我说,什么时候是附加的,为什么?
原标题:Entity Framework telling me an object is attached when it isn t - why?

我希望在数据库中更新一个目标。 I m New to EF but have made a fair bit ofread. 显然,我的做法是错误的,但我不理解为什么。 整个《刑法》中所提到的背景是,随着《刑法》的开始和立即处理,新出现的内容。 这里是我的更新方法——我想要在数据库中更新这个观点,它有4个色人特性,我也希望将其改动留给数据库:

    public void Update(View view)
    {
        var original = Read(view.Username, view.ViewId);

        original.ViewName = view.ViewName;

        ProcessChanges<CostCentre, short>(Context.CostCentres, original.CostCentres, view.CostCentres, "iFinanceEntities.CostCentres", "CostCentreId");

        ProcessChanges<LedgerGroup, byte>(Context.LedgerGroups, original.LedgerGroups, view.LedgerGroups, "iFinanceEntities.LedgerGroups", "LedgerGroupId");

        ProcessChanges<Division, byte>(Context.Divisions, original.Divisions, view.Divisions, "iFinanceEntities.Divisions", "DivisionId");

        ProcessChanges<AnalysisCode, short>(Context.AnalysisCodes, original.AnalysisCodes, view.AnalysisCodes, "iFinanceEntities.AnalysisCodes", "AnalysisCodeId");

        int test = Context.SaveChanges();
    }

第一,我从数据库中获取原始资料,因为我想将其收集资料与新的一套收集资料进行比较。 这应确保添加和删除正确的次级目标。 我比较了使用这一处理方法的每项收集:

    private void ProcessChanges<TEntity, TKey>(ObjectSet<TEntity> contextObjects, ICollection<TEntity> originalCollection, ICollection<TEntity> changedCollection, string entitySetName, string pkColumnName) 
        where TEntity : class, ILookupEntity<TKey>
    {
        List<TKey> toAdd = changedCollection
            .Select(c => c.LookupKey)
            .Except(originalCollection.Select(o => o.LookupKey))
            .ToList();

        List<TKey> toRemove = originalCollection
            .Select(o => o.LookupKey)
            .Except(changedCollection.Select(c => c.LookupKey))
            .ToList();

        toAdd.ForEach(a =>
        {
            var o = changedCollection.Single(c => c.LookupKey.Equals(a));

            AttachToOrGet<TEntity, TKey>(entitySetName, pkColumnName, ref o);
            originalCollection.Add(o);
        });

        toRemove.ForEach(r =>
        {
            var o = originalCollection.Single(c => c.LookupKey.Equals(r));
            originalCollection.Remove(o);
        });
    }

这与旧的收集比较,并努力增加哪些物品和去除。 请注意,所有收藏品都含有执行国际激光测距装置的物体。

My problems occur on the line where I call AttachToOrGet. This method I got from elsewhere on stackoverflow. I m using this because I was often getting a message saying that "An object with the same key already exists in the ObjectStateManager" when attaching a new subobject. Hopefully you ll understand my confusion around this when I post the code of this method below:

    public void AttachToOrGet<TEntity, TKey>(string entitySetName, string pkColumnName, ref TEntity entity)
        where TEntity : class, ILookupEntity<TKey>
    {
        ObjectStateEntry entry;
        // Track whether we need to perform an attach
        bool attach = false;
        if (Context.ObjectStateManager.TryGetObjectStateEntry(new EntityKey(entitySetName, pkColumnName, entity.LookupKey), out entry))
        //if (Context.ObjectStateManager.TryGetObjectStateEntry(Context.CreateEntityKey(entitySetName, entity), out entry))
        {
            // Re-attach if necessary
            attach = entry.State == EntityState.Detached;
            // Get the discovered entity to the ref
            entity = (TEntity)entry.Entity;
        }
        else
        {
            // Attach for the first time
            attach = true;
        }
        if (attach)
            Context.AttachTo(entitySetName, entity);
    }

从根本上说,如果该实体还没有附属于该实体的话。 But 我的法典正在归还有关背景的错误。 入境线,但最后线上有一个例外,即“物体在目标Manager中已经存在同样的关键”。 对我来说,这是自相矛盾的。

就我而言,我不想简单地谈一点。 有时需要20分钟时间来撰写储存的程序。 简便的数据库更新。 坦率地说,我不关心随附的东西和n子,因为我不想跟踪变化或制造轴心或zy装,或做任何其它的EF为我提供的东西。 我只想提一个非常简单的标语,利用服务器之间的最低次数更新数据库。 这种复杂性如何? 请有人帮助我——我一整天花了!

<><>><>>Update<>>>>>

这里,我爱爱爱护团:

public interface ILookupEntity<TKey>
{
    TKey LookupKey { get; }
    string DisplayText { get; }
}

如何在成本中心实施:

public partial class CostCentre : IFinancialCode, ILookupEntity<short>
{
    #region IFinancialCode Members

    public short ID { get { return CostCentreId; } }

    public string DisplayText { get { return string.Format("{0} - {1}", Code, Description); } }

    #endregion

    #region ILookupEntity Members

    public short LookupKey
    {
        get { return ID; }
    }

    #endregion ILookupEntity Members
}
问题回答

诚然,我通过这一努力找到了解决办法,但我可以说是理解的。 关键内容是在我发表评论后由@Slauma进行核对。 我想对我使用正确的实体名称等进行检查,因此,我在Atach ToOrGet方法顶端附近有以下线:

        var key = new EntityKey(entitySetName, pkColumnName, entity.LookupKey);

        object temp;
        if (!Context.TryGetObjectByKey(key, out temp))
            throw new Exception(string.Format("No entity was found in {0} with key {1}", entitySetName, entity.LookupKey));

奇怪的是,仅靠这个办法就解决了这一问题。 出于某种原因,一旦我叫TryGetObjectByKey,就任反对国。 TryGetObjectState 进入电话实际上开始查找附属实体。 奇卢。 如果有人能够解释,我会热爱。

顺便提一下,我还需要列入以下法典,但这只是因为就我而言,模范实体位于与情况本身不同的组合中。

        Assembly assembly = typeof(CostCentre).Assembly;
        Context.MetadataWorkspace.LoadFromAssembly(assembly);




相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

How to Add script codes before the </body> tag ASP.NET

Heres the problem, In Masterpage, the google analytics code were pasted before the end of body tag. In ASPX page, I need to generate a script (google addItem tracker) using codebehind ClientScript ...

Transaction handling with TransactionScope

I am implementing Transaction using TransactionScope with the help this MSDN article http://msdn.microsoft.com/en-us/library/system.transactions.transactionscope.aspx I just want to confirm that is ...

System.Web.Mvc.Controller Initialize

i have the following base controller... public class BaseController : Controller { protected override void Initialize(System.Web.Routing.RequestContext requestContext) { if (...

Microsoft.Contracts namespace

For what it is necessary Microsoft.Contracts namespace in asp.net? I mean, in what cases I could write using Microsoft.Contracts;?

Separator line in ASP.NET

I d like to add a simple separator line in an aspx web form. Does anyone know how? It sounds easy enough, but still I can t manage to find how to do it.. 10x!

热门标签