不重复记录不能插入到多对多的关系表(Cannot insert into Many to Many

2019-10-28 09:28发布

我有以下对象:大多数属性中删除。

public class WorkQueue : IEntity
{
    public WorkQueue()
    {

    }

    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public Guid Id { get; set; }

    public virtual ICollection<Action> Actions { get; set; }
    public virtual ICollection<Role> AllowableRoles { get; set; }
}

public class Role: IEntity
{
    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public Guid Id { get; set; }

    public virtual ICollection<Action> Actions { get; set; }
    public virtual ICollection<WorkQueue> AllowedWorkQueues { get; set; }
}

public class Action: IEntity
{
    public Action()
    {
        Roles = new HashSet<Role>();
    }

    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public Guid Id { get; set; }
    public string Name { get; set; }


    public virtual Guid WorkQueue_Id { get; set; }
    public virtual WorkQueue WorkQueue { get; set; }

    public virtual ICollection<Role> Roles { get; set; }
}

而下面的实体类型配置:

public class WorkQueueConfig : EntityTypeConfiguration<WorkQueue>
{
    public WorkQueueConfig()
    {
        HasMany(x => x.AllowableRoles)
            .WithMany(x => x.AllowedWorkQueues)
            .Map(m =>
            {
                m.MapLeftKey("WorkQueueId");
                m.MapRightKey("RoleId");
                m.ToTable("AllowableRolesByWorkQueue");
            });

        HasMany(x => x.Actions)
            .WithRequired(x => x.WorkQueue)
            .WillCascadeOnDelete(false);
    }
}

public class ActionConfig: EntityTypeConfiguration<Action>
{
    public ActionConfig()
    {
        HasMany(x => x.Roles)
            .WithMany(x => x.Actions)
            .Map(m =>
            {
                m.MapLeftKey("ActionId");
                m.MapRightKey("RoleId");
                m.ToTable("ActionRole");
            });

        HasRequired(x => x.WorkQueue)
            .WithMany(x => x.Actions)
            .WillCascadeOnDelete(false);
    }
}

这将导致在下面,我很高兴有:

问题是,当我尝试插入一个新的WorkQueue ,我的Role在数据库中的条目被复制。 我已插入所有可能的Role的实体。

我读了一些解决方案,但没有一个似乎为我工作。 我曾尝试以下:

仅发送角色的的标识的,对DB。 这没有奏效。

private async Task<WorkQueue> SetRolesAsPerContext(WorkQueue workQueue)
    {
        if (workQueue.AllowableRoles != null && workQueue.AllowableRoles.Count > 0)
        {
            ICollection<Role> roles = await _repository.GetAllAsync<Role>();
            IEnumerable<Guid> selectedRoleIds = workQueue.AllowableRoles.Select(s => s.Id);
            var filteredRoles = roles.Where(r => selectedRoleIds.Contains(r.Id))
                .Select(r => new Role() { Id = r.Id })
                .ToList();

            //set workqueue roles
            workQueue.AllowableRoles = filteredRoles;

            if (workQueue.Actions != null && workQueue.Actions.Count > 0)
            {
                foreach (SimO2O.Models.Action action in workQueue.Actions)
                {
                    IEnumerable<Guid> selectedActionRoleIds = action.Roles.Select(s => s.Id);
                    action.Roles = roles.Where(r => selectedActionRoleIds
                        .Contains(r.Id))
                        .Select(r => new Role() { Id = r.Id })
                        .ToList();
                }
            }
        }

        return workQueue;
    }

我也曾尝试连接的Role对象,以目前的情况下,这样的EntityFramework不会看到他们作为新的对象,最后,尝试设置EntityStateDetached ,但这样下去创建重复的角色。

public async Task<Guid> CreateWorkQueueAsync(WorkQueue workQueue, string userName)
    {
        //set Permissions on same context
        _repository.AttachEntity(workQueue.AllowableRoles);
        _repository.ModifyState(workQueue.AllowableRoles, System.Data.Entity.EntityState.Detached);

        _repository.Create(workQueue, workQueue.AllowableRoles, userName);
        await _repository.SaveAsync();
        return workQueue.Id;
    }

下面是我在写的方法_repository类用于连接和设置EntityState

public void AttachEntity<TEntity>(TEntity entity) where TEntity : class, IEntity
    {
        Context.Set<TEntity>().Attach(entity);
    }

    public void AttachEntity<TEntity>(ICollection<TEntity> entities) where TEntity : class, IEntity
    {
        foreach (TEntity entity in entities)
            Context.Set<TEntity>().Attach(entity);
    }

    public void ModifyState<TEntity>(TEntity entity, EntityState state) where TEntity : class, IEntity
    {
        Context.Entry(entity).State = state;
    }

    public void ModifyState<TEntity>(ICollection<TEntity> entities, EntityState state) where TEntity : class, IEntity
    {
        foreach (TEntity entity in entities)
            Context.Entry(entity).State = state;
    }

我缺少的是在这里吗?

文章来源: Cannot insert into Many to Many relationship table without duplicating records