【问题标题】:Confused about attaching/detaching entities in EF对在 EF 中附加/分离实体感到困惑
【发布时间】:2009-08-24 12:45:16
【问题描述】:

使用 ASP.NET MVC 和 Entity Framework,当我需要将更改写入数据库时​​遇到一些附加/分离错误。

首先是我从存储库中获取记录的方法:

public PublishedApplication GetPublishedApplication(int id)
{
    return dal.ExecuteFirstOrDefault(
        context.PublishedApplication.Include("Customers")
        .Where(w => w.Id == id));
}

请注意,这不是分离的,它有 MergeOption = AppendOnly。

另一个地方,我在我的 repo 中调用一个方法来将客户附加到应用程序:

public void AttachCustomer(int applicationId, int customerId)
{
    var app = new PublishedApplication{ Id = applicationId};
    var customer = new Customer { Id = customerId};

    try
    {
        context.AttachTo("PublishedApplication", app);
        context.AttachTo("Customer ", customer );

        app.Customers.Add(customer);

        context.SaveChanges();
    }
    catch
    {
        throw;
    }
}

当然,这会给我一个错误,即对象(应用程序和客户)已附加到对象上下文。

所以我需要在我的存储库中分离我的对象。这也更正确,因为我不需要在网络上抛出“查询相关信息”。但是我该怎么做呢?如果我在GetPublishedApplication 方法中分离实体,我的相关数据图就会丢失,我负担不起。我需要我网站上其他地方的图表。也不能使用合并选项NoTracking

那么我有什么选择呢?

提前致谢!

【问题讨论】:

  • 你说你不能使用 NoTracking。想知道为什么不呢?这似乎非常适合您的需求。
  • 似乎一方面您希望您的实体分离? IE。所以你得到'无变化跟踪'。但是你说你不能使用NoTracking Merge Option?这对我来说似乎很奇怪。亚历克斯
  • 如果我设置了NoTracking,是不是还是会跟踪对象的相关图呢?

标签: c# asp.net-mvc entity-framework


【解决方案1】:

我认为,重新附加实体并不容易。
也许这篇文章会帮助你: Reattaching Entity Graphs with the Entity Framework on codeproject.com

【讨论】:

    猜你喜欢
    • 2012-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-22
    相关资源
    最近更新 更多