我目前有一个班级:
[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
的主键和外键,所以我不知道为什么它会给我这个错误。怎么了?
答案 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)
我将两个实体映射到一个表。显然,实体框架中不允许这样做,所以这就是我收到错误的原因。