Peurr Peurr - 2 months ago 11
ASP.NET (C#) Question

Efficient data saving, like system (example)

I'm building a school project with several class mates. We've ran into a (minor) problem.

There will be a 'forum' where classmates can post questions and where others can give answers/replies to.

We're working with an ASP.NET Core application (web api). So, here's the case: we want classmates to be able to like questions, answers and replies.

I've built some models, what we could do is make a 'like' table for each section (questions, answers, replies). But I think that's a little inefficient.

public class Question
{
public Guid Id { get; set; }
public User User { get; set; }
public string Title { get; set; }
}

public class Answer
{
public Guid Id { get; set; }
public User User { get; set; }
public string Body { get; set; }
}

public class Comment
{
public Guid Id { get; set; }
public User User { get; set; }
public string Body { get; set; }
}


Now my question is, what would be the most efficient way to save these likes? I've built a like model already, but I'm not sure what would be the best.

public class Like
{
public Guid Id { get; set; }
public User User { get; set; }
}


I've tried somethings like adding an
ICollection<Like>
to the Question, Answer and Comment model, but can't figure out on how to use this.

I hope someone has a solution.

Answer

Something along these lines should get you started. Adopt your Question, Answer and Comment classes:

public class Question
{
    public Guid Id { get; set; }
    public User User { get; set; }
    public string Title { get; set; }
    public string Body { get; set; }
    public List<Answer> Answers {get; set; }
    public List<Comment> Comments {get; set; }
}

public class Answer
{
    public Guid Id { get; set; }
    public User User { get; set; }
    public string Body { get; set; }
    public List<Comment> Comments {get; set; }
}

public class Comment
{
    public Guid Id { get; set; }
    public User User { get; set; }
    public string Body { get; set; }
}

Then create an enum with the possible types of posts:

public enum TypeOfPost
{
Question,
Answer,
Comment
}

Use this enum in your Like class:

public class Like
{
   public Guid Id { get; set; }
   public User User { get; set; }
   public TypeOfPost PostType { get; set; }
   public Guid LikedPostId { get; set; }
}