Search code examples
c#entity-frameworkasp.net-coreentity-framework-coreasp.net-core-mvc

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'


This error is thrown when I try to edit my post.

Here is my code:

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);
}

The debugger stops the code at

var news = await _context.News.FindAsync(id);

Code for my model is

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; }

Any idea on how to fix this?


Solution

  • According to the documentation:

    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.

    Therefore, if the primary key in your case has int type, then the FindAsync() parameter should be the same type int.