【发布时间】: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