【问题标题】:Adding & Updating Foreign key in Entity Framework v1在实体框架 v1 中添加和更新外键
【发布时间】:2009-08-12 06:23:54
【问题描述】:

我正在使用 .NET 3.5 SP1。 我创建了实体'Category',基于表'category_table'和'MyUser',基于表'App_User_table'。

CREATE TABLE category_table (
 catg_id int,
 catg_name varchar(50),
 catg_description varchar(250)
 )

CREATE TABLE App_User_table (
 userid int,
 username varchar(50),
 fullname varchar(50), catg_id int,
 fullAddress varchar(200),
 comments varchar(1000),CONSTRAINT FK_1 FOREIGN KEY (catg_id) REFERENCES Category_table (catg_id) 
)

public class Category: System.Data.Objects.DataClasses.EntityObject{    
 public int  CategoryId{get; set;}   
 public string CategoryName {get; set;} 
  ....
}

public class AppUser : System.Data.Objects.DataClasses.EntityObject{   
 public int Uid {get; set;}   
 public string UserName {get; set;}   
 public string Name {get; set;}   
 public string Address {get; set;}
 public string Comment {get; set;} 
 public Category category_table  { .. } 
 public System.Data.Objects.DataClasses.EntityReference<Category> category_tableReference {...}
 ...........   
}

我想在 ASP.NET MVC 应用程序中添加和更新 AppUser 实体。

添加:

//create entity with passed values
AppUser user = new AppUser(){Uid=id, ....  }
//Set EntityReference
user.category_tableReference.EntityKey = new System.Data.EntityKey("MyContext.CategorySet", "CategoryId", categoryIdSelected);
myContext.AddToCategorySet(user);
myContext.SaveChanges(true);

更新:

//create entity with passed Id 
AppUser user = new AppUser(){Uid=id  }
//Attach entitymyContext.AttachTo("UserSet", user);
//Update entity with passed values
user.Address = addr;
....

//从DropDownList更新选择的CategoryId

user.category_tableReference.EntityKey = new System.Data.EntityKey("MyContext.CategorySet", "CategoryId", categoryId);

Update 方法不会更新数据库中的 CategoryId。

请告知,解决问题的最佳方法是什么?

谢谢。

【问题讨论】:

    标签: entity-framework foreign-keys


    【解决方案1】:

    这是我在 MVC 应用程序中用于更新的方法:

    // Put the original Stub Entities for both the original User and its 
    // original category. The second part is vital, because EF needs to know 
    // original FK values to successfully do updates in 3.5 SP1
    AppUser user = new AppUser {
        Uid = id, 
        Category = new Category {
            CategoryId = OriginalCategoryID
        }
    };
    ctx.AttachTo("UserSet", user);
    
    // Then do this:
    if (user.Category.CategoryId != categoryIdSelected)
    {
        Category newCategory = new Category {CategoryId = CategoryIdSelected};
        // Attach because I assume the category already exists in the database
        ctx.AttachTo("CategorySet", newCategory);
        user.Category = newCategory;
    }
    
    // Update entity with passed values
    user.Address = addr;
    ....
    

    正如您所见,您需要能够从某个地方获取 OriginalCategoryID,我建议在表单上设置一个隐藏字段。

    这将完成您需要的一切。查看Tip 26 - How to avoid database queries using Stub Entities 了解有关 Stub Entity 技巧的更多信息。

    希望对你有帮助

    亚历克斯

    【讨论】:

      【解决方案2】:

      更新:请参阅 Craig Stuntz 和 Alex James 的 cmets - 我的立场已得到纠正 - 似乎可以简单地更新“EntityKey”以实现您所要求的。我在这里的帖子不再适用

      在版本 1 中,Entity Framework 不能只插入外键值 - 您需要将“Category”对象实例添加到“AppUser”的 Cateogry 导航属性:

      //create entity with passed values
      AppUser user = new AppUser(){Uid=id, ....  }
      
      // set the Category navigation property
      Category newUserCategory  = Category.GetbyID(4); // or whatever you need
      user.Category = newUserCategory;
      
      myContext.AddToCategorySet(user);
      myContext.SaveChanges(true);
      

      在今年晚些时候(2009 年)与 .NET 4.0 一起发布的 EF v4 中,您将能够只设置外键值来实现两个实体之间的关联。

      在此处查看更多信息:

      但是现在,您需要设置完整的对象 - 只是引用是不行的。

      马克

      【讨论】:

      • 这不是真的。除了 Alex 的“存根对象”建议之外,您还可以仅使用 ID 新建一个 EntityKey 并将其分配给引用。
      • 好吧,Alex 的建议和我的基本一样——你只需要创建一个“完整”的 Category 对象——你不能只将值“4”分配给外键列——你需要提供一个“类别”对象。
      • Alex 的建议不涉及数据库读取。您的建议涉及数据库读取。那是不同的恕我直言。要分配 EntityKey,您可以执行类似(猜测名称)user.CategoryReference.EntityKey = new EntityKey("MyEntities.Categories", "Cid", 4);
      • @Craig:当然,我同意——亚历克斯的建议更巧妙,但事实仍然存在——你必须提供一个完整的“类别”对象。我会尝试你的 EntityKey 方法 - 我不知道这在 EFv1 中有效 - 我会试一试!
      • 您当然也可以使用 EntityKey 方法。唯一的事情是对于更新,您还需要在将其更改为最新值之前指定原始 EntityKey。在 3.5 中关系(即 PK-FK 对)是并发检查的一部分,因此为了更改一端(即 FK)您需要提供原始 FK 值,以便 ef 可以删除原始 PK-FK 对并插入新的 PK-FK 对。正如您所知道的 FK 关联,这会发生变化。主要是因为 FK 现在在结构上是实体的一部分,这意味着您不再需要原始值来更新它。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多