【问题标题】:MVC Code First using Navigation Properties使用导航属性的 MVC 代码优先
【发布时间】:2017-11-10 09:58:42
【问题描述】:

这是一个简单的 cmets 和消息系统。他们还有两个演员: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; }
}

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

【问题讨论】:

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


    【解决方案1】:

    您应该在Actor 类中添加对Comments 和Messages 的附加引用,并使用InversePropertyAttribute 将它们映射到相应的属性。也可以直接声明FKs:

    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; }
    }
    

    【讨论】:

    • 恕我直言...非常感谢 :) InverseProperty 是我的解决方案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-07
    相关资源
    最近更新 更多