创建没有外键的导航属性

我有两个像这样的课程:


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


基本上我想要的是零或一到零或多的关系。


我如何保持关卡独立但能够将关卡添加到配置文件?


绝地无双
浏览 100回答 1
1回答

慕码人2483693

您不能完全删除外键,否则,您希望如何链接两个实体(即表)?相反,您可以做的是拥有一个可为空的 FK,这将有效地使关系为零或一到多。在您的GameLevel课程中,将导航属性添加为以下内容的集合UserGameProfile:public class GameLevel{&nbsp; &nbsp; [Key]&nbsp; &nbsp; [DatabaseGenerated(DatabaseGeneratedOption.Identity)]&nbsp; &nbsp; public int Id { get; set; }&nbsp; &nbsp; public string Name { get; set; }&nbsp; &nbsp; public double PointsMin { get; set; }&nbsp; &nbsp; public double PointsMax { get; set; }&nbsp; &nbsp; public virtual ICollection<UserGameProfile> UserGameProfiles { get; set; }}然后在UserGameProfile类中,使属性可以为GameLevelId空:public class UserGameProfile&nbsp;{&nbsp; &nbsp; // ...&nbsp; &nbsp; // ...&nbsp; &nbsp; public int? GameLevelId { get; set; }&nbsp; &nbsp; [ForeignKey("GameLevelId")]&nbsp; &nbsp; public virtual GameLevel GameLevel { get; set; }}这应该可以工作,甚至不必使用 Fluent API。
打开App,查看更多内容
随时随地看视频慕课网APP