c#中不能使用Count()
本文关键字:Count 不能 | 更新日期: 2023-09-27 18:05:27
我有一个项目使用。net CORE,我的控制器有System。Linq了。当我尝试使用Count()时,我仍然有错误。
using xxx.Core;
using xxx.DataAccess;
using xxx.DataAccess.Azure;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Linq;
namespace xxx.Api.Controllers
{
[Route("api/[controller]")]
public class ResourcesController : Controller
{
private static DocumentDB _db = new DocumentDB();
[HttpGet("{id}")]
public IActionResult Get(string id)
{
using (var unitOfWork = new UnitOfWork(_db))
{
var r = unitOfWork.Resources.Get(id);
Models.resource result = ConvertResourceModel(r);
if (result.Count() != 1)
{
return NotFound();
}
else
{
return Ok(result);
}
}
}
if (result.Count() != 1)的那行在Count()上有一个错误,说"resource不包含Count的定义,也没有扩展方法Count接受resource类型的第一个参数…"我的资源模型定义如下:
public class resource
{
public string id { get; set; }
public string description { get; set; }
public List<translations> translations { set; get; }
public DateTime modified { get; set; }
public DateTime accessed { get; set; }
public string by { get; set; }
}
public class translations {
public string language { set; get; }
public string content { set; get; }
public DateTime modified { get; set; }
public DateTime accessed { get; set; }
public string by { get; set; }
}
我不知道为什么。任何帮助吗?谢谢!
您的资源不是一个列表而是一个对象。更好的实现应该是这样的:
[HttpGet("{id}")]
public IActionResult Get(string id)
{
using (var unitOfWork = new UnitOfWork(_db))
{
var r = unitOfWork.Resources.Get(id);
if (r == null)
{
return NotFound();
}
return Ok(ConvertResourceModel(r));
}
}