When using EF Core to query MySQL in C#, the primary key column name is incorrect
P粉736935587
P粉736935587 2023-08-17 13:45:14
0
1
578
<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粉736935587
P粉736935587

reply all(1)
P粉610028841

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template