【发布时间】:2015-07-09 05:44:36
【问题描述】:
我将 POCO 与 EF4 结合使用,并且某些实体处于多对多关系中,在我的例子中是 User 类的对象和 PrivilegeGroup 类的对象。
这是 User 类的样子:
public class User
{
public int UserID { set; get; }
public string UserName { get; set; }
public string UserPassword { get; set; }
public bool IsActive { get; set; }
public List<PrivilegeGroup> PrivilegeGroups { get; set; }
}
这就是 PrivilegeGroup 类的样子:
public class PrivilegeGroup
{
public int PrivilegeGroupID { get; set; }
public string Name { get; set; }
public List<User> Users { get; set; }
public List<HasPrivilege> HasPrivileges { get; set; }
}
我已经扩展了 ObjectContext 类 如下:
public class AdminMDSContext : ObjectContext
{
public AdminMDSContext(string connectionString)
: base(connectionString)
{
this.DefaultContainerName = "MDSUsers_Entities";
_users = CreateObjectSet<User>();
_privilegeGroups = CreateObjectSet<PrivilegeGroup>();
}
private ObjectSet<User> _users;
private ObjectSet<PrivilegeGroup> _privilegeGroups;
public ObjectSet<User> Users
{
get { return _users; }
}
public ObjectSet<PrivilegeGroup> PrivilegeGroups
{
get { return _privilegeGroups; }
set { _privilegeGroups = value; }
}
}
这些实体的查询和插入工作正常,但删除有问题,即我想从一个用户中删除 PrivilegeGroup 而无需 db 往返,但我不知道该怎么做。
谁能帮帮我?
【问题讨论】:
-
你试过什么?在我看来
yourUser.PrivilegeGroups.Remove(yourPrivilegeGroup); context.SaveChanges();` 应该可以完成这项工作,但我可能错了。您能否展示一些您尝试实际执行删除的代码? -
using (AdminMDSContext context = new AdminMDSContext(GetConnStringHTMLDecoded())) { var usVar = from us in context.Users where us.UserID == userId select us;用户用户 = usVar.SingleOrDefault
(); var pgVar = from pg in context.PrivilegeGroups where pg.PrivilegeGroupID == privilegeGroupId select pg; PrivilegeGroup privilegeGroup = pgVar.SingleOrDefault (); if (user.PrivilegeGroups == null) {user.PrivilegeGroups = new List ();} user.PrivilegeGroups.Add(privilegeGroup); user.PrivilegeGroups.Remove(privilegeGroup); context.SaveChanges(); } -
好吧,上面的代码肯定看起来不太乐观。简而言之,我创建了具有按所需 id 过滤的数据的对象,对于 User 类的对象,我初始化了 List
然后我添加并从中删除我的 PrivilegeGroup 对象。之后,我保存了对上下文的更改。我对数据库进行了两次查询以查找一个用户和一个权限组,但我没有任何删除 sql 查询。我想要相反,只是执行了删除 sql 查询。我不知道我在这里做错了什么。 -
我通过显式加载 List
解决了这个问题,但我仍然有 3 个 db 访问权限,我希望只有一个,这将只需要删除 sql 查询。
标签: c# entity-framework-4 many-to-many poco