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

标签 c# entity-framework foreign-key-relationship one-to-one

我有两个类:

主类:

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 个左右相似的类,一对一的关系运行良好。这是唯一给我以下错误的错误:

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; }
}

关于c# - EF 代码第一个 1 对 1 关系错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34599846/

相关文章:

c# - Peek 如何在启用分区的服务总线队列中工作?

c# - 我需要在 LINQ 查询后强制 Dispose 吗?

entity-framework - 在 ASP.NET MVC Controller 中管理 Entity Framework ObjectContext 的依赖项注入(inject)的正确方法是什么?

entity-framework - EF Core 2.0/2.1 - 如何有效地处理不常访问的大型列?

Oracle - 主键和外键

c# - Entity Framework 4,插入外键值而不是 ID

c# - 使用注释和 IValidatableObject 进行递归验证

c# - .NET C# : HttpClient and the TaskCanceledException exception

python - 与 SQLAlchemy 的多对多模型连接

c# - 传递 id 并在 javascript 中查找元素