为同一张表创建多个一对一键(非组合键)

时间:2019-06-27 09:51:58

标签: entity-framework asp.net-core foreign-keys

另一个表的主表以一对一关系两次引用其ID。

显然,重复了注释和api之类的操作,现在已经尝试了许多组合。只有一种关系,一切正常。

 public class MasterLanguage {
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    [Required]
    [StringLength(50)]
    public string Language { get; set; }

    [ForeignKey("TaughtInLanguageId")]
    public UserLearningLanguage masterUserLearningLanguageT { get; set; }
    [ForeignKey("LearningLanguageId")]
    public UserLearningLanguage masterUserLearningLanguageL { get; set; }
}

 public class UserLearningLanguage {
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    public int LearningLanguageId { get; set; }
    public MasterLanguage MasterLanguageL { get; set; }

    public int TaughtInLanguageId { get; set; }
    public MasterLanguage MasterLanguageT { get; set; }
}

modelBuilder.Entity<MasterLanguage>()
            .Property(b => b.MasterLanguageDateAdded)
            .HasDefaultValueSql("getdate()");

        modelBuilder.Entity<MasterLanguage>()
            .HasOne<UserLearningLanguage>(s => s.masterUserLearningLanguageT)
            .WithOne(t => t.MasterLanguageT)
            .HasForeignKey<UserLearningLanguage>(ad => ad.TaughtInLanguageId)
            .OnDelete(DeleteBehavior.Restrict);

        modelBuilder.Entity<MasterLanguage>()
            .HasOne<UserLearningLanguage>(s => s.masterUserLearningLanguageL)
            .WithOne(l => l.MasterLanguageL)
            .HasForeignKey<UserLearningLanguage>(ad => ad.LearningLanguageId)
            .OnDelete(DeleteBehavior.Restrict);

当前获取:在表'UserLearningLanguages'上引入FOREIGN KEY约束'FK_UserLearningLanguages_MasterLanguages_LearningLanguageId'可能会导致循环或多个级联路径。指定ON DELETE NO ACTION或ON UPDATE NO ACTION,或修改其他FOREIGN KEY约束。无法创建约束或索引。查看以前的错误。

我永远都不想从MasterLanguage表中删除任何内容,如果从User表中删除了一条记录,它应该只删除该记录。

0 个答案:

没有答案