【问题标题】:Identity with efcore for customer and staffefcore 为客户和员工提供身份
【发布时间】:2021-08-12 11:48:28
【问题描述】:

我目前为我的电子商务应用程序的客户和员工设计表格,并且我正在使用 asp.net 核心身份。我想知道我是否应该为员工和客户使用 1 个表用户(又名 aspnetuser),还是应该将它们分开并使用用户 ID 作为外键?如果用外键将它们分开 2 个新表是用户 ID,我如何使用用户管理器为员工和客户创建帐户? 谢谢。

【问题讨论】:

    标签: entity-framework asp.net-core asp.net-identity


    【解决方案1】:

    您可以扩展IdentityUser 基类,以创建带有其他字段的表,例如:

    public class MyIdentityUser : IdentityUser<string>
        {
            public string FirstName { get; set; }
            public string LastName { get; set; }
            public string Type { get; set; }
    ...
    

    Type 字段可以是StaffCustomer

    或者您可以使用一个或多个附加表并使用 Microsoft.ASpNetCore.IdentityIdentityUser 类中定义的 Id

        public class IdentityUser<TKey> where TKey : IEquatable<TKey>
        {
            /// <summary>
            /// Initializes a new instance of <see cref="IdentityUser{TKey}"/>.
            /// </summary>
            public IdentityUser() { }
    
            /// <summary>
            /// Initializes a new instance of <see cref="IdentityUser{TKey}"/>.
            /// </summary>
            /// <param name="userName">The user name.</param>
            public IdentityUser(string userName) : this()
            {
                UserName = userName;
            }
    
            /// <summary>
            /// Gets or sets the primary key for this user.
            /// </summary>
            [PersonalData]
            public virtual TKey Id { get; set; }
    ...
    

    您可以定义 Id 字段的类型,就像我之前的示例一样,并在自定义表格中的相关字段(如 IdentityUserId)上使用相同的类型。

    如果您扩展基本 IdentityUser 类,您需要使用此声明创建派生上下文,如下所示:

    namespace MyProject.Infrastructure.Contexts
    {
        public class MyContext : IdentityDbContext<MyIdentityUser>
        {
    ...
    

    【讨论】:

    • 你认为我应该使用 TPH 来解决这类问题吗?那么使用角色呢?
    • 角色是另一种解决方案。在这种情况下,您不再需要派生的 IdentityUser 类中的 Type 字段,但过滤更加困难。我将角色用于授权范围,而不是用于分析范围。我更喜欢将单独的 entity 用于个人数据,而 IdentityUser + IdentityRole 仅用于身份验证和授权。
    • 感谢 Babyface_Developer。如果您觉得可以,请不要忘记接受答案。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2018-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多