简体   繁体   中英

setting up objects for code first EF6 foreign key issue

I have the following models (pseudocode):

Post {
 int id

 List<Like> likes
 List<Comment> comments
}

Comment {
 int id

 List<Like> likes

 int PostId -- FK to Post
 Post Post
}

Like {
 int id

 int CommentId -- FK to Comment
 Comment Comment

 int PostId -- FK to Post
 Post Post
}

the important bit here is that my like has a foreign key to both post and comment , because each post and comment can have its own instance (liking a post vs liking a comment).

Entity framework is complaining about multiple cascade paths, what's the correct way to build these entities?

If you delete a post it will delete the likes and the comments. Your likes will delete the comments.

Multiple cascade paths because you are deleting comments twice.

You can either edit the generated code first code and change "cascadeDelete:true" to false or you can fix your classes.

You should have a LikeComment class.

 public class Comment { public int Id { get; set; } public List<CommentLike> Likes { get; set; } public int PostId { get; set; } public Comment() { Likes = new List<CommentLike>(); } } public class Like { public int Id { get; set; } }
public class Post
{
    public int Id { get; set; }
    public List<PostLike> Likes { get; set; }
    public List<PostComment> Comments { get; set; }
    public Post()
    {
        Likes = new List<PostLike>();
        Comments = new List<PostComment>();
    }
}


public class PostComment : Comment
{
    public int PostId { get; set; }
    [ForeignKey("PostId")]
    public virtual Post Post { get; set; }
}
public class LikeComment : Comment
{
    public int LikeId { get; set; }
    [ForeignKey("LikeId")]
    public virtual Like Like { get; set; }
}


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

public class CommentLike : Like
{
    public int CommentId { get; set; }
    [ForeignKey("CommentId")]
    public virtual Comment Comment { get; set; }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM