0

我目前有一堂课:

[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。Title列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,所以我不知道为什么它会给我这个错误。怎么了?

4

2 回答 2

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]属性放在您认为是关系子级的类中。

于 2012-05-29T13:55:54.953 回答
0

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

于 2012-05-29T16:55:07.347 回答