代码之家  ›  专栏  ›  技术社区  ›  Unbreakable

如何在ASP中处理多对多相同的表(用户)。Net MVC 5-Fluent API

  •  1
  • Unbreakable  · 技术社区  · 7 年前

    我正在学习ASP。Net MVC 5和我一直坚持一个基本的数据库设计。 送交

    推荐模式:

    Public class Referral
    {
         [Key]
            public int ReferralId { get; set; }
            public Company Company { get; set; }
            public int CompanyId { get; set; }
            public ApplicationUser User { get; set; }
            public string CandidateId { get; set; } // Application User ID of person asking for referral
            public string ReferrerId { get; set; } // Application user ID of person referring the candidate
    }
    

    应用程序用户模型

      public class ApplicationUser : IdentityUser
        {
            public ICollection<Referral> Referrals { get; set; }
            // rest prop removed for brevity sake
        }
    

    现在,假设A(推荐人)引用B(候选人)。我的桌子行如下所示。

    ReferralId     CompanyId     CandidateId   ReferrerId
    
    1              1             B             A
    

    到目前为止,一切都很好。但我想在转诊表上建立FK关系。我不熟悉Fluent API,但我试过如下方法。

        // one candidate can have many referrals
        dBModelBuilder.Entity<ApplicationUser>()
        .HasMany(u => u.Referrals)
        .WithRequired(u => u.User)
        .HasForeignKey(u => u.CandidateId)
        .WillCascadeOnDelete(false);
    
        //one referrar can have many referrals
        dBModelBuilder.Entity<ApplicationUser>()
        .HasMany(u => u.Referrals)
        .WithRequired(u => u.User)
        .HasForeignKey(u => u.ReferrerId);
    

    预期行为:我预期有两个FK的关系。一旦我有了它,我就可以相应地工作了。请引导我到这里。我对这一切都不熟悉。

    enter image description here

    1 回复  |  直到 7 年前
        1
  •  1
  •   Ivan Stoev    7 年前

    关系,你需要

    所以在 侧面更换 Referrals 具有以下内容的属性:

    public class ApplicationUser : IdentityUser
    {
        // ...
        public ICollection<Referral> ReferrerOf { get; set; }
        public ICollection<Referral> CandidateOf { get; set; }
    }
    

    许多的 User 属性:

    public class Referral
    {
        // ...
        public ApplicationUser Candidate { get; set; }
        public ApplicationUser Referrer { get; set; }
    }
    

    modelBuilder.Entity<ApplicationUser>()
        .HasMany(u => u.CandidateOf) // <--
        .WithRequired(r => r.Candidate) // <--
        .HasForeignKey(r => r.CandidateId)
        .WillCascadeOnDelete(false);
    
    modelBuilder.Entity<ApplicationUser>()
        .HasMany(u => u.ReferrerOf) // <--
        .WithRequired(r => r.Referrer) // <--
        .HasForeignKey(r => r.ReferrerId);
    

    只要正确关联导航属性,它们的名称实际上并不重要。