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

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

創建沒有外鍵的導航屬性

創建沒有外鍵的導航屬性

C#
絕地無雙 2022-10-23 14:01:27
我有兩個像這樣的課程:[Table("GameLevels", Schema = "ref")]public class GameLevel{    [Key]    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]    public int Id { get; set; }    public string Name { get; set; }    public double PointsMin { get; set; }    public double PointsMax { get; set; }}[Table("GameProfiles", Schema = "usr")]public class UserGameProfile {    [Key]    [ForeignKey("ApplicationUser")]    public string Id { get; set; }    public int GamesPlayed { get; set; }    public double Points { get; set; }    public int WinCount { get; set; }    public int LossCount { get; set; }    public int DrawCount { get; set; }    public int ForfeitCount { get; set; }    public int GameLevelId { get; set; }    public virtual GameLevel Level { get; set; }    public virtual ApplicationUser ApplicationUser { get; set; }}實體框架構建它,以便UserGameProfile具有指向GameLevel. 我想這是因為GameLevelId財產。有什么方法可以讓我在沒有外鍵的情況下生成表格和導航屬性?我試過了:modelBuilder.Entity<UserGameProfile>().HasOptional<GameLevel>(x => x.Level).WithMany();但是隨后數據庫無法構建。出現此錯誤:在模型生成期間檢測到一個或多個驗證錯誤:Project.Domain.Data.UserGameProfile_Level::多重性與關系“UserGameProfile_Level”中角色“UserGameProfile_Level_Target”中的引用約束沖突。因為從屬角色中的所有屬性都不可為空,所以主體角色的多重性必須為“1”。基本上我想要的是零或一到零或多的關系。我如何保持關卡獨立但能夠將關卡添加到配置文件?
查看完整描述

1 回答

?
慕碼人2483693

TA貢獻1860條經驗 獲得超9個贊

您不能完全刪除外鍵,否則,您希望如何鏈接兩個實體(即表)?相反,您可以做的是擁有一個可為空的 FK,這將有效地使關系為零或一到多。


在您的GameLevel課程中,將導航屬性添加為以下內容的集合UserGameProfile:


public class GameLevel

{

    [Key]

    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]

    public int Id { get; set; }

    public string Name { get; set; }

    public double PointsMin { get; set; }

    public double PointsMax { get; set; }


    public virtual ICollection<UserGameProfile> UserGameProfiles { get; set; }

}

然后在UserGameProfile類中,使屬性可以為GameLevelId空:


public class UserGameProfile 

{

    // ...

    // ...


    public int? GameLevelId { get; set; }


    [ForeignKey("GameLevelId")]

    public virtual GameLevel GameLevel { get; set; }

}

這應該可以工作,甚至不必使用 Fluent API。


查看完整回答
反對 回復 2022-10-23
  • 1 回答
  • 0 關注
  • 96 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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