本文介绍了ASP MVC5 身份用户抽象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to build N-tire web application with default Identity 2 provider. So, my Data layer contains pure c# classes with model definition, without any externad dependency. But it is impossible to link some classes to my Application User without adding AspNet.Identity reference.

我尝试制作一个 User 类的接口:

I have tried to make an interface of User class:

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

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

And in Infrastructure layer substitute it with implementation:

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

但是实体框架不会在实体之间创建关系.

But entity framework does not creates relation between entities.

是否有任何正确"的方法来实现这一点,或者是否需要添加引用?

Is there any 'right' way do implement this or it is necesarry to add reference?

推荐答案

有一个变通方法,在我看来它非常丑陋但有效.

There's a workaround, which is pretty ugly in my opinion but works.

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

You will need 2 classes, one for the User and another for the ApplicationUser. ApplicationUser must have all properties of User. Like this:

//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 类的同一个表.像这样:

Now, the trick is mapping the User class to the same table of the ApplicationUser class. Like this:

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

        ToTable("AspNetUsers");
    }
}

希望能帮到你!

这篇关于ASP MVC5 身份用户抽象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-17 06:59
查看更多