编程语言
首页 > 编程语言> > c#-EF代码第1对1关系错误

c#-EF代码第1对1关系错误

作者:互联网

我有两节课:

主班:

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

    [ForeignKey("CourseOutcomes")]
    public int CourseOutcomesId { get; set; }

    public virtual CACourseOutcomesModel CourseOutcomes { get; set; }
}

相关类:

public class CACourseOutcomesModel
{
    [Key, ForeignKey("CourseDetail")]
    public int CourseOutcomesId { get; set; }

    [Required]
    public virtual CCourseDetailModel CourseDetail { get; set; }
}

我有10个左右的相似类,具有1对1的关系,可以很好地工作.这是唯一给我以下错误的人:

CACourseOutcomesModel_CourseDetail_Target: : Multiplicity is not valid in Role ‘CACourseOutcomesModel_CourseDetail_Target’ in
relationship ‘CACourseOutcomesModel_CourseDetail’. Because the
Dependent Role properties are not the key properties, the upper bound
of the multiplicity of the Dependent Role must be ‘
‘.*

知道我哪里出错了吗?请需要新鲜的眼睛.谢谢!

解决方法:

在一对一关系中,一端必须是主体,另一端必须是从属关系,因此您不能在两面都具有FK属性.删除主体(CCourseDetailModel)和CACourseOutcomesModel中的FK属性,您不需要使用Required属性.使用ForeignKey属性,您已经在告诉EF谁是从属端.

在Fluent Api中将是:

modelBuilder.Entity<CACourseOutcomesModel>()
            .HasRequired(p => p.CourseDetail)
            .WithOptional(p => p.CourseOutcomes);

所以您的模型应该是这样的:

public class CCourseDetailModel
{
    [Key]
    //[DatabaseGenerated(DatabaseGeneratedOption.Identity)] don't need this, it's the configuration by default.
    public int CourseDetailId { get; set; }

    public virtual CACourseOutcomesModel CourseOutcomes { get; set; }
}

public class CACourseOutcomesModel
{
    [Key, ForeignKey("CourseDetail")]
    public int CourseOutcomesId { get; set; }

    public virtual CCourseDetailModel CourseDetail { get; set; }
}

标签:one-to-one,foreign-key-relationship,c,entity-framework
来源: https://codeday.me/bug/20191027/1945033.html