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

mas*_*one 6 c# entity-framework entity-framework-core asp.net-core-mvc asp.net-core

当我尝试编辑我的帖子时,会引发此错误。

这是我的代码:

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);
}
Run Code Online (Sandbox Code Playgroud)

调试器将代码停止在

var news = await _context.News.FindAsync(id);
Run Code Online (Sandbox Code Playgroud)

我的模型的代码是

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; }
Run Code Online (Sandbox Code Playgroud)

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

Jac*_*daw 5

根据文档:

FindAsync(对象[])

查找具有给定主键值的实体。如果上下文正在跟踪具有给定主键值的实体,则会立即返回该实体,而无需向数据库发出请求。否则,将在数据库中查询具有给定主键值的实体,如果找到该实体,则将其附加到上下文并返回。如果没有找到实体,则返回 null。

因此,如果您的情况下的主键具有int类型,则FindAsync()参数应该是相同的类型int