ArgumentException: 调用 'DbSet<News>.Find' 的位置 0 处的键值为 'string' 类型,与 属性 类型的 int' 不匹配

ArgumentException: The key value at position 0 of the call to 'DbSet<News>.Find' was of type 'string', which does not match the property type of int'

当我尝试编辑 post.

时抛出此错误

这是我的代码:

public async Task<IActionResult> Edit(string id)
{
    if (id == null)
    {
        return NotFound();
    }
    // issue 
    var news = await _context.News.FindAsync(id);
    if (news == null)
    {
        return NotFound();
    }
    return View(news);
}

调试器在

处停止代码
var news = await _context.News.FindAsync(id);

我的模型代码是

public int id { get; set; }
[Required(ErrorMessage = "Enter your name.")]
public string Author { get; set; }
[Required(ErrorMessage = "Enter the title.")]
public string Title { get; set; }
[Required(ErrorMessage = "Enter the issued date.")]
[DataType(DataType.Date)]
public DateTime IssueDate { get; set; }
[Required(ErrorMessage = "Enter a message.")]
[DataType(DataType.MultilineText)]
public string Body { get; set; }

知道如何解决这个问题吗?

根据文档:

FindAsync(Object[])

Finds an entity with the given primary key values. If an entity with the given primary key values is being tracked by the context, then it is returned immediately without making a request to the database. Otherwise, a query is made to the database for an entity with the given primary key values and this entity, if found, is attached to the context and returned. If no entity is found, then null is returned.

因此,如果您的主键具有 int 类型,那么 FindAsync() 参数应该是相同类型 int.

最可靠的方法是

var _id=Convert.ToInt32(id);

  var news = await _context.News.FirstOrDefaultAsync(i=>i.id==_id);

但也许换个动作更好?

public async Task<IActionResult> Edit(int? id)