簡體   English   中英

創建沒有外鍵的導航屬性

[英]Create navigation property without foreign key

我有兩個這樣的課程:

[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”。

基本上,我想要的是零或一對零或許多關系。

如何保持關卡獨立但可以向配置文件添加關卡?

您不能完全刪除外鍵,否則,您如何期望兩個實體(即表)被鏈接? 您可以做的是使用可為空的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。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM