无法更新外键引用(导航属性)

时间:2011-03-14 12:25:00

标签: c# entity-framework asp.net-mvc-3 repository-pattern entity-framework-ctp5

我知道这似乎是一个重复的条目,但我红了所有与我的问题相关的帖子,我找不到解决方案。一周左右,我遇到了这个问题。也许我做了一些设计问题或者我不知道。问题是我无法更新导航属性,我尝试了几个选项,每次我得到一个不同的错误或重复。好的,这是场景:

  

我有一个对象“列表”
  int ID
  字符串名称
  int SendType
  类别类别//这些是导航属性
  产品//这些是导航属性

类别和产品不了解与List的关系。我使用由CTP5 DbContext Generator模板生成的POCO类,我为每个实体使用一个存储库。在每个存储库中都有对dbcontext的引用。

这是控制器:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(int id, List list)
    {
        if (!ModelState.IsValid)
            return View(list);

        List originalList = this._listRepository.Get(id);
        TryUpdateModel(originalList, "List", new string[] { "Name", "SendType"});
        //Here's I tried to update manually like this
        if (list.category.id != originalList.category.id)
        {
           Category category = this._categoryRepository.GetNoTracking(list.category.id);
           originalList.Category = category; 
        }
        if (list.product.id != originalList.product.id)
        {
           Product product = this._productRepository.GetNoTracking(list.product.id);
           originalList.Product = product; 
        }
        this._listRepository.Save(); //Here's I call only the SubmitChanges()
        return RedirectToAction("Index");                               
    }

如果我直接尝试收到错误

  

实体类型'DbEntityEntry'不是当前上下文模型的一部分

因为我修改了实体类别或产品的状态(它们来自另一个上下文)

如果我在不修改关联的情况下提交更改,则会收到错误

  

'IDCategory'是参考密钥,无法更新

等等......任何建议都会受到赞赏,如果我错了,我也可以修改视图模型。我没有想法!感谢

更新

    //This is in List Repository
    public override void Save()
    {           
        checkReferencies();
        db.SaveChanges();            
    }

    private void checkReferencies()
    {          
         foreach (var entry in db.ChangeTracker.Entries()
                               .Where(e => e.State == EntityState.Modified || e.State == EntityState.Added))
         {
             if (ObjectContext.GetObjectType(entry.Entity.GetType()).Name.Equals("List"))
             {
                 /*In this case I tried to update my object directly with the object that comes form the form
                 if (entry.CurrentValues.GetValue<int>("IDList").ToString() != "0" )
                 {
                     db.Entry(entry.Entity).State = EntityState.Modified;
                 }    */                 
                 if (((List)entry.Entity).Product != null)
                 {
                     db.Entry(((List)entry.Entity).Product).State = EntityState.Unchanged;
                 }
                 if (((List)entry.Entity).Category != null)
                 {
                     db.Entry(((List)entry.Entity).Category).State = EntityState.Unchanged;
                 }
             }
             else if (ObjectContext.GetObjectType(entry.Entity.GetType()).Name.Equals("Product") 
                   || ObjectContext.GetObjectType(entry.Entity.GetType()).Name.Equals("Category"))
             {
                 //here I attach the entry that I added
                 db.Category.Attach((Category)db.Entry(entry).Entity.Entity);

             }
         }
    }

    //This is in categoryRepository
    public Category GetNoTracking(int id)
    {            
        return db.Category.AsNoTracking().Single(l => l.IDCategory == id);
    }

    //This is in productRepository
    public Product GetNoTracking(int id)
    {            
        return db.Product.AsNoTracking().Single(l => l.IDProduct == id);
    }

    //This is my DbContext
    namespace BusinessManagerEmail.Models
    {
         using System;
         using System.Data.Entity;

         public partial class DBMailMarketingEntities : DbContext
         {
             public DBMailMarketingEntities()
             : base("name=DBMailMarketingEntities")
             {
             }

             public DbSet<Category> Category { get; set; }
             public DbSet<Customer> Customer { get; set; }
             public DbSet<Subscription> Subscription { get; set; }
             public DbSet<List> List { get; set; }
             public DbSet<Product> Product { get; set; }
        }
   }

这是所涉及的所有代码。谢谢!

1 个答案:

答案 0 :(得分:0)

删除checkReferencies,因为:

    您的示例中的
  • List未被修改,因此方法的第一部分将不会被执行。
  • Product无法转换为Category并附加到DbSet。它会抛出异常。
  • Category已经附加在Addes州(这是错误的,因为它会再次插入类别)。再次附加实体将抛出异常。

只需将CategoryProduct附加到listRepository的上下文,然后再将其设置为List

或者更好地完全重写代码并在repostiories之间共享上下文。

相关问题