在Entity Framework v1中添加和更新外键

dev*_*dev 3 entity-framework foreign-keys

我正在使用.NET 3.5 SP1.我根据表'app_User_table'创建了基于表'category_table'和'MyUser'的实体'Category'.

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 {...}
 ...........   
}
Run Code Online (Sandbox Code Playgroud)

我想在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);
Run Code Online (Sandbox Code Playgroud)

更新:

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

//从DropDownList更新选定的CategoryId

user.category_tableReference.EntityKey = new System.Data.EntityKey("MyContext.CategorySet", "CategoryId", categoryId);
Run Code Online (Sandbox Code Playgroud)

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

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

谢谢.

Ale*_*mes 8

以下是我在MVC应用程序中用于Update的方法:

// 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;
....
Run Code Online (Sandbox Code Playgroud)

如您所见,您需要能够从某个地方获取OriginalCategoryID,我建议在表单上使用隐藏字段.

这将完成您需要的一切.查看提示26 - 如何使用存根实体避免数据库查询以获取有关存根实体技巧的更多信息.

希望这可以帮助

亚历克斯