问题
我想在我的详细信息页面上显示一只宠物。我无法理解如何编写 LINQ(Method Syntax) 从数据库中提取单个宠物/物品。
到目前为止我的理解
使用 LINQ 时,它的闪亮目的是能够遍历IEnumerable
数据库中的数组或列表。当您查看我HomeController
的 .
要求
使用方法语法,我应该使用什么查询来拉单个宠物?
家庭控制器.cs
[HttpGet("pet/{PetId}")]
public IActionResult Detail(Pet singlePet)
{
List<Pet> Animal = _context.Pets
//***MISSING QUERY CODE HERE***
return View("Pet", singlePet);
}
详细信息.cshtml
@model PetViewModel
<div>
<h1>Pet Shelter</h1>
@foreach (Pet creature in Model.Pets)
{
<h3>Details about: @creature.Name</h3>
<div>
<p>Pet Type: @creature.Type</p>
<p>Description: @creature.Description</p>
<p>Skill One:@creature.Skill1</p>
<p>Skill Two:@creature.Skill2</p>
<p>Skill Three:@creature.Skill3</p>
</div>
}
</div>
PetViewModel.cs
using System.Collections.Generic;
namespace petShelter.Models
{
public class PetViewModel
{
public Pet Animal { get; set; }
public List<Pet> Pets { get; set; }
public List<Owner> Owners { get; set; }
public Owner Owner { get; set; }
}
}
宠物.cs
using System;
using System.ComponentModel.DataAnnotations;
namespace petShelter.Models
{
public class Pet
{
[Key]
public int PetId { get; set; }
[Required]
public string Name { get; set; }
[Required]
public string Type { get; set; }
[Required]
public string Description { get; set; }
public string Skill1 { get; set; }
public string Skill2 { get; set; }
public string Skill3 { get; set; }
public DateTime CreatedAt { get; set; }
public DateTime UpdatedAt { get; set; }
public Owner Owner { get; set; }
public int? OwnerId { get; set; }
}
}