大家好,
我正在学习使用 EF 进行攀爬,我对使用 EF 的 CRUD 有基本的了解,但是现在我有一个具有导航属性的表(我怀疑是桥表),所以我需要添加价值桥表,我想我可以用导航属性来做。
问题解释:
原始部分数据库图
部分 EF 模型图
我写的代码:
protected void BtnAddUser_Click(object sender, EventArgs e)
{
DBEntities entities = new DBEntities();
var usr = new User();
//I thought I would add an Roles object into usr.UserRoles.Add(usrRoles);
//but UserRoles have only two fields ,RoleTypeId and UserId
//var usrRoles = new Roles()
//{Id=0,RoleDescription="dfdfdf",RoleType="WebSite Admin"};
usr.UserName = TxtbxUserName.Text;
usr.Password = TxtBxPassword.Text;
usr.Email = TxtbxEmail.Text;
usr.CreateDate = DateTime.Now;
usr.LastActivityDate = DateTime.Now;
usr.IsEnabled = true;
//What to Add in the .Add method
usr.UserRoles.Add(
entities.User.AddObject(usr);
int result = entities.SaveChanges();
LblMsg.Text = result == 1 ? "User created successfully." : "An error occured ,please try later.";
entities.Dispose();
}
更新(到目前为止我已经尝试过):
我从角色表中获取“网站管理员”角色并将其放入ObjectContext.UserRoles.Add(UserRoleWebsiteAdmin);
所以我在代码中所做的,
//Fetch WebsiteAdmin from Roles
var userRole = from usrRole in entities.Roles
where usrRole.Id == 1
select usrRole;
usr.UserName = TxtbxUserName.Text;
//same old code of usr.Property = someTextBox
//I have tried to type cast it LinqtoEntities result into Roles
usr.UserRoles.Add((Roles)userRole);
产生异常
PS:如果您需要更多说明,请告诉我。