c# - ASP MVC5 身份用户抽象

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

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

我尝试制作一个用户类的接口(interface):

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

但是 Entity Framework 不会创建实体之间的关系。

是否有任何“正确”的方法来实现这个或者是否需要添加引用?

最佳答案

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

您将需要 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");
    }
}

希望对您有所帮助!

关于c# - ASP MVC5 身份用户抽象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34862770/

相关文章:

c# - 使用 Pure Razor 时的动态 Web 控件

c# - 从母版页的代码后面访问 RadEditor 控件...当它存在时找不到任何 radEditor 控件...有什么问题吗?

asp.net - 如何在不使用表单的情况下将控件放在不同的内容占位符中

entity-framework - FirebirdSql.Data.FirebirdClient.FbException : too many open handles to database

c# - 如何通过LINQ获取单个对象?错误: The result of a query cannot be enumerated more than once

c# - Interop.CDO 的问题

C# - 对大文件进行霍夫曼编码需要太长时间

C# 控制台获取 Windows 10 强调色

javascript - 是否有帮助将 Prototype JavaScript 转换为 jQuery 的资源?

c# - Entity Framework Code First 不会将身份设置为是