不复制记录就无法插入多对多关系表

时间:2019-03-07 08:33:07

标签: c# sql .net visual-studio entity-framework-6

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

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);
    }
}

我对以下结果感到满意:

enter image description here

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

我已经阅读了一些解决方案,但似乎没有一个对我有用。我尝试了以下方法:

仅将角色的ID发送到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不会将它们视为新对象,最后,尝试将EntityState设置为Detached,但是这样会继续创建重复的角色。

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;
    }

我在这里想念什么?

0 个答案:

没有答案