1对1关系EF两个外键错误

时间:2016-08-30 20:43:03

标签: c# asp.net-mvc entity-framework

    public class Picture
        { 
            [Key]
            public int Id { get; set; }

            public int NewsId { get; set; }
            [ForeignKey("NewsId")]
            public virtual News News { get; set; }

            public int PostId { get; set; }
            [ForeignKey("PostId")]
            public virtual Post Post { get; set; }        
        }

    public class News
        {
            public int Id { get; set; }
            public virtual Picture Picture { get; set; }
        }

public class Post
    {
        public int Id { get; set; }
        public virtual Picture Picture { get; set; }
    }

例外:

  

无法确定之间关联的主要结束   类型' Project.BusinessObjects.Photo'和   ' Project.BusinessObjects.Student&#39 ;.主要目的   必须使用以下任一方式显式配置此关联   关系流畅的API或数据注释。

怎么了?

1 个答案:

答案 0 :(得分:0)

我认为你可以通过在其他类的键之上创建新的[key]数据注释来解决问题。像这样:

public class Picture
{ 
    [Key]
    public int Id { get; set; }

    [ForeignKey("News")]
    public int NewsId { get; set; }
    public virtual News News { get; set; }

    [ForeignKey("Post")]
    public int PostId { get; set; }        
    public virtual Post Post { get; set; }        
}

public class News
{
    [Key]
    public int Id { get; set; }
    public virtual Picture Picture { get; set; }
}

public class Post
{
    [Key]
    public int Id { get; set; }
    public virtual Picture Picture { get; set; }
}