【问题标题】:How Configure one to Many Relationship From AspNetUsers Table To ... using Fluent API如何使用 Fluent API 配置从 AspNetUsers 表到...的一对多关系
【发布时间】:2021-10-24 02:59:21
【问题描述】:

​ 嗨

我有两张桌子

1.应用用户

2.销售

如何使用 Fluent API 在 DataContext.cs 类中配置一对多关系

从 AppUser 表 ID 到销售表用户 ID

继承自 IdentityUser 的 AppUser 表类

using System.Collections.Generic;
using Microsoft.AspNetCore.Identity;

namespace Domain
{
    public class AppUser : IdentityUser
    {
        public string DisplayName { get; set; }
        public string Bio { get; set; }
       
    }
}

销售表类

namespace Domain
{
    public class Sale
    {
        public int SaleID { get; set; }
        public int SaleAmount { get; set; }
        public int UserID { get; set; }

    }
}

谢谢。

【问题讨论】:

    标签: c# entity-framework .net-core entity-framework-core ef-fluent-api


    【解决方案1】:

    添加关系

    public class AppUser : IdentityUser
        {
            public string DisplayName { get; set; }
            public string Bio { get; set; }
    
             public virtual  ICollection<Sale> Sales { get; set; }
        }
    }
    
        public class Sale
        {
            public int SaleID { get; set; }
            public int SaleAmount { get; set; }
    
            public int UserID { get; set; }
            public virtual AppUser User { get; set; }
    
        }
    

    由于您使用的是 net core 5,在这种情况下您不需要任何流畅的 api

    但如果你使用其他版本,你可以添加

    modelBuilder.Entity<Sale>(entity =>
                {
                    entity.HasOne(d => d.User)
                       .WithMany(p => p.Sales )
                       .HasForeignKey(d => d.UserId);
                });
    

    【讨论】:

    • 我同意您的解决方案,但我建议您不要这样做。首先,SaleAppUser 经常位于不同的 DbContexts 中(尤其是如果 Identity 由 Visual Studio 或 dotnet 构建时)。身份甚至可能不在数据库中或在同一个数据库中;所以甚至可能无法设置一对多的关系。您应该使用身份 API,而不是表关系。最后,很大程度上取决于应用程序是否总是保存当前用户的 ID(“自助服务”)或者它可能是不同的用户(“客户服务”)。简而言之,不要这样做
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-06-23
    • 1970-01-01
    • 1970-01-01
    • 2014-12-03
    • 1970-01-01
    • 2016-06-08
    • 1970-01-01
    相关资源
    最近更新 更多