MVC代码首先使用导航属性

时间:2017-11-10 09:58:42

标签: c# asp.net asp.net-mvc ef-code-first navigation-properties

这是一个简单的评论和消息系统。他们还有两个演员:FromActor和ToActor ......我的代码是这样的:

 public class Comment
 {        
    public int Id { get; set; } 
    public string Title { get; set; }
    public string Text { get; set; }
    public virtual Actor AboutActor { get; set; }        
    public virtual Actor FromActor { get; set; }
 }

 public class Message
 {
    public int Id { get; set; }       
    public string Title { get; set; }       
    public string Text { get; set; }       
    public virtual Actor ToActor { get; set; }
    public virtual Actor FromActor { get; set; } 
}

public class Actor  
{       
    public int Id { get; set; }       
    public string Username { get; set; }
    public virtual List<Comment> Comments { get; set; }
    public virtual List<Message> Messages { get; set; }
}

我首先在代码中遇到导航道具问题。这是真的吗?我应该如何编辑解决方案的导航链接或模型?感谢...

1 个答案:

答案 0 :(得分:0)

您应该在Comment类添加对MessageActor的其他引用,并使用InversePropertyAttribute将它们与相应的属性进行映射。您也可以直接声明FK

public class Comment
{        
    //other stuff...
    public int AboutActorId { get; set; }        
    public int FromActorId { get; set; }
    public virtual Actor AboutActor { get; set; }        
    public virtual Actor FromActor { get; set; }
}

public class Message
{
    //other stuff...
    public int ToActorId { get; set; }        
    public int FromActorId { get; set; }
    public virtual Actor ToActor { get; set; }
    public virtual Actor FromActor { get; set; } 
}

public class Actor  
{       
    public int Id { get; set; }       
    public string Username { get; set; }

    [InverseProperty("AboutActor")]
    public virtual ICollection<Comment> CommentsAbout { get; set; }
    [InverseProperty("FromActor")]
    public virtual ICollection<Comment> CommentsFrom { get; set; }

    [InverseProperty("ToActor")]
    public virtual ICollection<Message> MessagesTo { get; set; }
    [InverseProperty("FromActor")]
    public virtual ICollection<Message> MessagesFrom { get; set; }
}