在实体框架中映射表时出现多重性问题

时间:2012-05-29 13:50:47

标签: entity-framework

我目前有一个班级:

[Table("TitleCategoryMovie", Schema = "dbo")]
public class TitleCategoryMovie
{
    [Key]
    public int Id { get; set; }

    public string CreatedBy { get; set; }
    public DateTime CreateDatetime { get; set; }
    public string UpdatedBy { get; set; }
    public DateTime UpdateDatetime { get; set; }

    [ForeignKey("Id")]
    public virtual Title Title { get; set; }
}

有一个名为Title的表格。并且每个TitleCategoryMovie都有相应的Title,但并非每个Title都有TitleCategoryMovie。标题列Id对于TitleCategoryMovie也是相同的。但是当我将两个实体类添加到我的DbContext时,它给了我一个错误:

Multiplicity is not valid in Role 'TitleCategoryMovieStandalone_Title_Source' in relationship 'TitleCategoryMovieStandalone_Title'. Because the Dependent Role refers to the key properties, the upper bound of the multiplicity of the Dependent Role must be �1�.

我已经在Id中将我的列TitleCategoryMovie定义为Title的主键和外键,所以我不知道为什么它会给我这个错误。怎么了?

2 个答案:

答案 0 :(得分:0)

您还应添加TitleId字段,并将其用作[ForeignKey]属性中的参数:

[Table("TitleCategoryMovie", Schema = "dbo")]
public class TitleCategoryMovie
{
    [Key]
    public int Id { get; set; }

    public string CreatedBy { get; set; }
    public DateTime CreateDatetime { get; set; }
    public string UpdatedBy { get; set; }
    public DateTime UpdateDatetime { get; set; }
    public int TitleId { get; set; }

    [ForeignKey("TitleId")]
    public virtual Title Title { get; set; }
}

评论后更新

我相信这样的事情应该有效:

[Table("TitleCategoryMovie", Schema = "dbo")]
public class TitleCategoryMovie
{
    [Key]
    public int Id { get; set; }

    public string CreatedBy { get; set; }
    public DateTime CreateDatetime { get; set; }
    public string UpdatedBy { get; set; }
    public DateTime UpdateDatetime { get; set; }

    public virtual Title Title { get; set; }
}

[Table("Title", Schema = "dbo")]
public class Title
{
    [Key]
    [ForeignKey("TitleCategoryMovie")]
    public int Id { get; set; }
    public string Something { get; set; }

    public virtual TitleCategoryMovie TitleCategoryMovie { get; set; }
}

您应该将[ForeignKey]属性放在您认为是该关系的子级的类中。

答案 1 :(得分:0)

我将两个实体映射到一个表。显然,实体框架中不允许这样做,所以这就是我收到错误的原因。