Home > Back-end >  how to get related model data in View model - One to Many Relation
how to get related model data in View model - One to Many Relation

Time:07-29

I know this is asked question but I confused what's the best practice to get data from a related model in View Model.

I want to show the review or comment data in view with category Name but in View Model CategoryId is just exist.

My question is should I add list of categories in Vm and find intended category by categoryId in View or there is better and optimized solution for this situation.

Review Model :

public class Review
{
    public int Id { get; set; }
    public string Author { get; set; }
    [MaxLength(500)]
    public string Body { get; set; }
    public int Rating { get; set; }
    public bool IsBuyer { get; set; }

    public int CategoryId { get; set; }
    public Category Category { get; set; }
}

Comment Model :

public class Comment
{
    public int Id { get; set; }
    public string Author { get; set; }
    [MaxLength(500)]
    public string Body { get; set; }

    public int CategoryId { get; set; }
    public Category Category { get; set; }
}

Category Model :

public class Category 
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Type { get; set; }
    public string Description { get; set; }

    public List<Comment> Comment { get; set; }
    public List<Review> Review { get; set; }
}

Vm :

public class RevComVm
{
    public Review Review { get; set; }
    public Comment Comment { get; set; }

    public List<Review> Reviews { get; set; }
    public List<Comment> Comments { get; set; }
}

CodePudding user response:

Finally, I added List of categories to View Model to access review/comment category and find specific record by CategoryId that saved in model using linq.

public class RevComVm
{
    public Review Review { get; set; }
    public Comment Comment { get; set; }

    public List<Review> Reviews { get; set; }
    public List<Comment> Comments { get; set; }
    public List<Category> Categories {get; set;}
}
  • Related