删除多对多关系

时间:2013-01-07 06:37:57

标签: entity-framework entity-framework-4 many-to-many entity-framework-5

我有两个班级:

public class User
{
    public int Id {get;set;}
    public string Username {get;set;}

    [InverseProperty("Users")]
    public virtual ICollection<Tag> Tags {get;set;}
}

public class Tag
{
    public int Id {get;set;}
    public string Title {get;set;}

    [InverseProperty("Tags")]
    public virtual ICollection<User> Users {get;set;}
}

这显然导致第3个表类似于称为UserTags的多对多关系,它只有两列,UserId和TagId。

现在假设我有100.000个用户和100.000个标签,平均每个Eser与1.000个标签有关系。我想从特定的User.Tags集合中删除单个标记,而不必在此之前加载所有标记。

最快的方法是什么?

1 个答案:

答案 0 :(得分:6)

试试这个:

// Create dummy objects for existing user and tag
var user = new User { Id = existingUserId };
var tag = new Tag { Id = existingTagId };
user.Tags.Add(tag);

// Start tracking user and related tag as unchanged
dbContext.Users.Attach(user);
// Remove relation between user and tag
user.Tags.Remove(tag);
dbContext.SaveChanges();