我正在使用 .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。
请告知,解决问题的最佳方法是什么?
谢谢。
最佳答案
这是我在 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 技巧的更多信息。
希望对你有帮助
亚历克斯
关于entity-framework - 在 Entity Framework v1 中添加和更新外键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1264498/