【问题标题】:ASP MVC5 Identity User AbstractionASP MVC5 身份用户抽象
【发布时间】:2016-04-24 02:22:15
【问题描述】:

我想使用默认的 Identity 2 提供程序构建 N-tire Web 应用程序。因此,我的数据层包含具有模型定义的纯 c# 类,没有任何外部依赖项。但是如果不添加 AspNet.Identity 引用,就不可能将某些类链接到我的应用程序用户。

我已经尝试做一个用户类的接口:

public interface ISystemUser
{
    string Id { get; set; }
    string Title { get; set; }
}

public class Place
{
    public int Id { get; set; }
    public string Address { get; set; }

    public ISystemUser User { get; set; }
}

在基础设施层用实现代替它:

public class ApplicationUser : IdentityUser, ISystemUser
{
    public string Title { get; set; }
}
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public ApplicationDbContext() : base("DefaultConnection", throwIfV1Schema: false)
    {
    }

    public DbSet<Place> Places { get; set; }
}

但实体框架不会创建实体之间的关系。

是否有任何“正确”的方式来实现这一点,或者是否需要添加参考?

【问题讨论】:

    标签: c# asp.net entity-framework architecture asp.net-identity


    【解决方案1】:

    有一个解决方法,在我看来这很丑陋,但有效。

    您将需要 2 个类,一个用于 User,另一个用于 ApplicationUserApplicationUser 必须具有 User 的所有属性。像这样:

    //Domain Layer
    public class User
    {
         public string Id { get; set; } 
         public string Title { get; set; }
    }
    
    //Infrastructure Layer
    public class ApplicationUser
    {
         public string Title { get; set; }
    }
    

    现在,诀窍是将User 类映射到ApplicationUser 类的同一个表。像这样:

    public class UserConfig : EntityTypeConfiguration<User>
    {
        public UserConfig()
        {
            HasKey(u => u.Id);
    
            ToTable("AspNetUsers");
        }
    }
    

    希望对你有帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-04-07
      • 1970-01-01
      • 1970-01-01
      • 2015-07-31
      • 2019-01-31
      • 2014-03-31
      • 1970-01-01
      相关资源
      最近更新 更多