问题描述
我正在使用具有Code-First方法的Entity Framework 6,而我希望将两个实体放在同一个表中。我做错了什么? [Table(Review)]
public class Review
{
public int Id {get;组; }
public PictureInfo PictureInfo {get;组; }
public int PictureInfoId {get;组;
}
[Table(Review)]
public class PictureInfo
{
[Key,ForeignKey(Review)]
public int ReviewId {get;组; }
public Review Review {get;组;
}
我得到的错误:
实体类型'PictureInfo'并且'Review'不能共享表'Review',因为它们不在同一类型层次结构中,或者与它们之间的匹配主键没有有效的一对一外键关系。
我做错了什么?
似乎问题是这个关系被解释为一对一..1而不是一对一。
检查结束的外键 int PictureInfoId
不需要/忽略,所以它的不可空性没有使审查结束的关系需要。删除这个不需要的键并将[Required]属性添加到PictureInfo导航属性中解决它。
这是更正的Review类。
[Table(Review)]
public class Review
{
public int Id {get;组; }
[必需]
public PictureInfo PictureInfo {get;组; }
}
I'm using Entity Framework 6 with a Code-First approach, and I want two entities to be put in the same table. What am I doing wrong?
[Table("Review")]
public class Review
{
public int Id { get; set; }
public PictureInfo PictureInfo { get; set; }
public int PictureInfoId { get; set; }
}
[Table("Review")]
public class PictureInfo
{
[Key, ForeignKey("Review")]
public int ReviewId { get; set; }
public Review Review { get; set; }
}
The error I get:The entity types 'PictureInfo' and 'Review' cannot share table 'Review' because they are not in the same type hierarchy or do not have a valid one to one foreign key relationship with matching primary keys between them.
What am I doing wrong?
Seems like the problem was that the relationship was interpreted as one-to-0..1 instead of one-to-one.
The foreign key int PictureInfoId
on the Review end was unneeded/ignored, so its non-nullability did not make the Review end of the relationship required. Removing this unneeded key and adding the [Required] attribute to the PictureInfo navigational property solved it.
Here's the corrected Review class.
[Table("Review")]
public class Review
{
public int Id { get; set; }
[Required]
public PictureInfo PictureInfo { get; set; }
}
这篇关于实体框架表拆分:不在同一类型层次结构中/不具有有效的一对一外键关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!