I am learning how to query a Mysql database in C# and am receiving an error that there is an invalid column in the column list, but I can’t figure out where that column name (ToDoId) is coming from.
There are only two columns in the table (model below) and the primary key in mysql is Id
. Where is that ToDoId
coming from and how can I force it to be Id
?
I looked at all the sample code (from here) and I believe I have updated everything to add my new table properly.
This is my model:
public class ToDo
{
public Guid Id { get; set; }
public string ToDoName { get; set; } = null!;
public ICollection<ToDo> ToDos { get; set; }
public ToDo()
{
ToDos = new HashSet<ToDo>();
}
}
This is where I get the error – at the query :
public class ToDoRepository : IToDoRepository
{
private readonly DatabaseContext _context;
public ToDoRepository(DatabaseContext context)
{
_context = context;
}
// The _context.ToDo below is defined as: public virtual DbSet<ToDo> ToDo { get; set; } = null!;
public IQueryable<ToDo> Query => _context.ToDo.AsQueryable();
// error occurs here ...
public IReadOnlyList<ToDo> List => Query
.ToList();
}
Error:
MySqlConnector.MySqlException: Unknown column ‘t.ToDoId’ in ‘field list’
3
Answers
EF Core has the hability to infer how you’re models are related to eachother and define some properties without you needing to do anything just based on names.
This can be extremely helpful sometimes, but it can mess things up as well, and I think that’s what’s happening here.
If you look at the example you sent, in the DatabaseContext they’re explicitely defining the keys DatabaseContext.cs
In this case, you might want to do something like this:
Keep it simple use EF conventions and rename your primary key to:
classNameID, so in your case:
or use Key attribute as described here:
friendly suggestion name your class Todo
You have an extra
ICollection
property, which EF is interpreting as a self-referencing foreign key column.Just remove it.