通用存储库UoW修改不更新FK集合

时间:2017-06-18 20:59:50

标签: c# entity-framework repository-pattern unit-of-work

我有2个型号:

拥有角色集合的用户

拥有用户集合的角色

这种关系以这种方式编码:

public class User : IBaseEntity<int>
{
    public User()
    {
        Roles = new HashSet<Role>();
    }
    public int ID { get; set; }
    public string Username { get; set; }
    public string DisplayName { get; set; }
    public string Email { get; set; }
    public bool Enabled { get; set; }
    [NotMapped]
    public bool IsAuthorized { get; set; }
    public virtual ICollection<Role> Roles { get; set; }
}

public class Role : IBaseEntity<int>
{
    public Role()
    {
        Users = new HashSet<User>();
    }
    public int ID { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public bool Enabled { get; set; }
    public virtual ICollection<User> Users { get; set; }
}

使用以下流畅的API配置:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();

        modelBuilder.Entity<Role>()
            .HasMany(e => e.Users)
            .WithMany(e => e.Roles)
            .Map(m => m.ToTable("UserRole").MapLeftKey("RoleId").MapRightKey("UserId"));
            .HasDatabaseGeneratedOption(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.None);

    }

这适用于添加和获取用户,正确加载了他们的角色集合,但是我的UnitOfWork模式上的.modify方法没有更新用户的角色集合:

public bool ModifyUser(User user)
    {
        try
        {
            user.Roles.Clear();
            if (user.IsAuthorized)
            {
                // Add admin role to user
                Role role = _roleRepository.GetMatching(r => r.ID == 1, "Users");
                user.Roles.Add(role);
            }

            _userRepository.Modify(user); // <- this is not updating the UserRole table at all.
            _userRepository.UnitOfWork.Commit();

            return true;
        }
        catch (Exception ex)
        {
            ExceptionHandler.HandleExceptionService(ex);
            return false;
        }
    }

我使用的通用存储库模式使用相同的UnitOfWork实例化存储库:

public class Repository<TEntity, TKey> : IRepository<TEntity, TKey>
    where TEntity : class, IBaseEntity<TKey>
{
    private readonly IQueryableUnitOfWork _currentUoW;


    public Repository(IQueryableUnitOfWork unitOfWork)
    {
        _currentUoW = unitOfWork;
    }


 public static void ConfigureContainer()
    {
        var container = new Container();
        container.Options.DefaultScopedLifestyle = new WebApiRequestLifestyle();

        //Infrastructure UoW, Repositories, etc
        container.Register<IQueryableUnitOfWork, MainUnitOfWork>(Lifestyle.Scoped);

Repository.cs:

public virtual void Modify(TEntity entity) { _currentUoW.SetModified<TEntity, TKey>(entity); }

0 个答案:

没有答案