亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何使列表和屬性指向同一實體

如何使列表和屬性指向同一實體

C#
慕桂英546537 2022-12-31 09:39:37
我是實體框架的新手,即使我知道如何在 Merise 中做到這一點,我也無法先使用代碼來做到這一點。在實體用戶中,我應該有一個外鍵“Promotion_Id”在實體促銷中,我應該有一個指向用戶實體的外鍵“Pilote_Id”。事情是這樣的:我還有一個促銷列表,它是促銷中所有用戶的列表。Pilote_Id 是該編隊飛行員的 Id,他當然是用戶。我嘗試了以下內容:    public class User : EntityWithId    {        public string FirstName { get; set; }        public string LastName { get; set; }        public string Email { get; set; }        public string Password { get; set; }        public string Phone { get; set; }        public virtual Promotion Promotion { get; set; }         }    public class Promotion : EntityWithNameAndId    {        //Site is another entity, the place where the promotion is         public virtual Site Site { get; set; }        public List<User> Users { get; set; }        public virtual User Pilote { get; set; }    }(注意:EntityWithId 僅包含一個 Id,而 EntityWithNameAndId 繼承自 EntityWithId,僅包含一個名稱)但它只會導致在名為 Promotion_Id 和 Promotion_Id1 的用戶中有 2 個外鍵。我已經通過改變讓整個事情都成功了public virtual User Pilote { get; set; }和public virtual Guid PiloteId { get; set; }但是我希望我的實體有一些一致性,所以..有沒有正確的方法來實現這個?
查看完整描述

1 回答

?
慕妹3242003

TA貢獻1824條經驗 獲得超6個贊

您可能需要使用顯式映射來實現此目的:


在您的上下文的 OnModelCreating() 中:


modelBuilder.Entity<User>()

   .HasOptional(u => u.Promotion)

   .WithRequired(p => p.Pilote)

   .Map(u => u.MapKey("PiloteId"); // EF6

   // .HasForeignKey("PilotId") // EF Core

這假設用戶可能有促銷活動,也可能沒有促銷活動,但所有促銷活動都有試點。Promotion.Users 可能會按照慣例在促銷表上使用 UserId 進行映射,但如果存在任何問題:


但是,這種方法有一個很大的警告,它與模式有關,而不是 EF。沒有任何限制/保護措施可以確保飛行員是與促銷相關的用戶之一。PiloteId 可以指向任何用戶,并且該用戶的 promotionId 可能不同。


在任何情況下,管理誰是飛行員的邏輯都需要通過代碼來完成,但這意味著要么檢查有效組合的 ID,要么像這樣:


如果一個用戶只能與 1 個促銷相關聯,并且該促銷中的一個用戶可以是試點,那么您可以考慮向用戶添加一個名為“IsPilot”的標志。


然后在促銷中:


public virtual ICollection<User> Users { get; set; } = new List<User>();

[NotMapped]

public User Pilote

{

   get { return Users.SingleOrDefault(u => u.IsPilote); }

   set 

   {   

      var newPilote = Users.Single(u => u.UserId == value.UserId); // Ensure the user nominated for Pilote is associated with this Promotion.

      var existingPilote = Pilote;

      if (existingPilote != null)

          existingPilote.IsPilote = false;

      newPilote.IsPilote = true;

   }

}

如果可以將用戶分配給多個促銷活動,那么您需要更新架構和映射以支持用戶和促銷活動之間的多對多關系,例如包含 UserId 和 PromotionId 的 UserPromotions 表。在這種情況下,我會考慮在此表/鏈接實體中分配 IsPilote,但這同樣需要邏輯來確保每次促銷圍繞 1 個試點進行規則,以及用戶是否可以成為多個促銷的試點。


查看完整回答
反對 回復 2022-12-31
  • 1 回答
  • 0 關注
  • 64 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號