Home  >  Q&A  >  body text

When using EF Core to query MySQL in C#, the primary key column name is incorrect

<p>I'm learning how to query a Mysql database in C#, but I'm getting an error saying there is an invalid column in the column list, but I can't figure out where that column name (ToDoId) comes from. </p> <p>There are only two columns in the table (model shown below), and the primary key in mysql is <code>Id</code>. Where does that <code>ToDoId</code> come from, and how do I force it to become <code>Id</code>? </p> <p>I've looked at all the sample code (from here) and I believe I've updated everything to add my new table correctly. </p> <p>This is my model:</p> <pre class="brush:php;toolbar:false;">public class ToDo { public Guid Id { get; set; } public string ToDoName { get; set; } = null!; public ICollection<ToDo> ToDos { get; set; } publicToDo() { ToDos = new HashSet<ToDo>(); } }</pre> <p>This is where I get the error - in the query: </p> <pre class="brush:php;toolbar:false;">public class ToDoRepository : IToDoRepository { private readonly DatabaseContext _context; public ToDoRepository(DatabaseContext context) { _context = context; } // The following _context.ToDo is defined as: public virtual DbSet<ToDo> ToDo { get; set; } = null!; public IQueryable<ToDo> Query => _context.ToDo.AsQueryable(); // The error occurred here... public IReadOnlyList<ToDo> List => Query .ToList(); }</pre> <p>Error message: </p> <blockquote> <p>MySqlConnector.MySqlException: Unknown column 't.ToDoId' in 'field list'</p> </blockquote><p><br /></p>
P粉736935587P粉736935587405 days ago524

reply all(1)I'll reply

  • P粉610028841

    P粉6100288412023-08-18 09:49:51

    Keep it simple, use EF conventions, and rename your primary key to:

    classNameID, so in your case:

    public Guid ToDoId { get; set; }

    Or use the Key attribute as described here:

    [Key]
    public Guid Id { get; set; }

    Friendly suggestion to name your class Todo

    reply
    0
  • Cancelreply