skip to Main Content

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


  1. 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

    modelBuilder.Entity<Calendar>(entity =>
    {
        entity.ToTable("Calendars");
    
        entity.HasKey(c => c.Id);
    
        entity.Property(c => c.Owner)
          .HasMaxLength(100);
    });
    

    In this case, you might want to do something like this:

    modelBuilder.Entity<ToDo>(entity =>
    {
        entity.ToTable("ToDos");
    
        entity.HasKey(c => c.Id);
    });
    
    Login or Signup to reply.
  2. Keep it simple use EF conventions and rename your primary key to:

    classNameID, so in your case:

    public Guid ToDoId { get; set; }
    

    or use Key attribute as described here:

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

    friendly suggestion name your class Todo

    Login or Signup to reply.
  3. You have an extra ICollection property, which EF is interpreting as a self-referencing foreign key column.

    public ICollection<ToDo> ToDos { get; set; }   // why is this here? 
    

    Just remove it.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search