我有下表:
public class Team
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[Required]
public string Name { get; set; }
public virtual ICollection<UserTeam> UserTeams { get; set; }
}
public class User
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[Required]
public string Name { get; set; }
public virtual ICollection<UserTeam> UserTeams { get; set; }
}
public class UserTeam
{
public long UserId { get; set; }
public User User { get; set; }
public long TeamId { get; set; }
public Team Team { get; set; }
}
多对多关系是在上下文中定义的:
modelBuilder.Entity<UserTeam>()
.HasKey(bc => new { bc.UserId, bc.TeamId });
modelBuilder.Entity<UserTeam>()
.HasOne(bc => bc.User)
.WithMany(b => b.UserTeams)
.HasForeignKey(bc => bc.UserId)
.OnDelete(DeleteBehavior.Restrict);
modelBuilder.Entity<UserTeam>()
.HasOne(bc => bc.Team)
.WithMany(c => c.UserTeams)
.HasForeignKey(bc => bc.TeamId)
.OnDelete(DeleteBehavior.Restrict);
我正尝试使用以下代码从小组中删除一些用户:
public async Task RemoveUsersFromTeam(int teamId, List<long> users)
{
Team existingTeam = await dbContext.Team.Include(x => x.UserTeams).FirstOrDefaultAsync(x => x.Id == teamId);
foreach (var user in users)
{
existingTeam.UserTeams.Remove(new UserTeam { UserId = user });
}
await dbContext.SaveAsync();
}
,但此查询不会删除我通过的用户。有人知道为什么会这样吗?
答案 0 :(得分:1)
您可以使用new和attach方法通过ID或通过传递实际实体来删除对象。
public async Task RemoveUsersFromTeam(int teamId, List<long> userIds)
{
Team existingTeam = await dbContext.Team.Include(x => x.UserTeams).FirstOrDefaultAsync(x => x.Id == teamId);
foreach (var userId in userIds)
{
var userTeam = existingTeam.UserTeams.FirstOrDefault(x => x.UserId == userId);
if(userTeam != null)
{
existingTeam.UserTeams.Remove(userTeam);
}
}
await dbContext.SaveAsync();
}
public async Task RemoveUsersFromTeam(int teamId, List<long> userIds)
{
Team existingTeam = await dbContext.Team.FirstOrDefaultAsync(x => x.Id == teamId);
foreach (var userId in userIds)
{
var userTeam = new UserTeam { UserId = userId });
dbContext.UserTeams.Attach(userTeam);
existingTeam.UserTeams.Remove(userTeam);
}
await dbContext.SaveAsync();
}
第二种方法不需要从数据库中选择UserTeam,在这方面效率会更高。但是,选项一可能更容易理解。您应该选择最适合您的情况。
我个人更喜欢选项2,因为include将选择整个实体,在某些情况下可能会超出必要。