Using list in a model value in LINQ query

前端 未结 2 420
有刺的猬
有刺的猬 2021-01-15 02:07

I am at very basic stage of asp.net MVC development. So sometimes I struggle with simple LINQ queries to work.

scenario-

I have A page that

2条回答
  •  無奈伤痛
    2021-01-15 02:46

    I slightly renovated your code with Foreign key relations ship. This will save your from using two different queries to your database (like what you are doing now).

    So if you Database Model looks like this -

    enter image description here

    Then you should have one viewmodel in your code in this way -

    public class ImageViewModel
    {
        public string ImageId { get; set; }
        public string ImageUrl { get; set; }
        public List Comments { get; set; }
    }
    

    And your controller action which will return all the results should be like this -

     public class ListController : Controller
        {
            public ActionResult Index()
            {
                ImageViewModel model;
                using (SampleEntities entities = new SampleEntities())
                {
                    model = (from p in entities.Images
                                         where p.ImageId == "1"
                                         select new ImageViewModel()
                                         {
                                             ImageId = p.ImageId,
                                             ImageUrl = p.ImageUrl,
                                             Comments = p.ImageComments.Select(pa => pa.Comment).ToList()
                                         }).FirstOrDefault();
                }
    
                return View(model);
            }
        }
    

    Finally the view which will display all the Image results -

    @model MVC.Controllers.ImageViewModel
    
    @{
        ViewBag.Title = "Index";
    }
    
    

    Index

    ImageViewModel


    @Html.DisplayNameFor(model => model.ImageId)
    @Html.DisplayFor(model => model.ImageId)
    @Html.DisplayNameFor(model => model.ImageUrl)
    @Html.DisplayFor(model => model.ImageUrl)

    @foreach (var item in Model.Comments) { @item
    }

    Output would be -

    enter image description here

提交回复
热议问题