为了账号安全,请及时绑定邮箱和手机立即绑定

创建没有外键的导航属性

创建没有外键的导航属性

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 关注
  • 99 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号