.NET Core Entity Framework throws Invalid object name when accessed as entity, but works with SQL

Viewed 3065

I'm working with Entity Framework Core, v6.2. I'm getting an error

SqlException: Invalid object name 'Cdef.CellDefinition'

when I try to access the DbSet directly, but using the same DbContext object, I can query the object directly using the FromSql command.

I've seen other answers saying to modify the conventions to remove PluralizingTableNameConvention, however since I'm doing a EntityFrameworkCore.DbContext that ModelBuilder does not have that option, and I don't see any evidence it is try to access a Pluralized name.

My entity is setup like:

[Table("Cdef.CellDefinition")]
public partial class CellDefinition
{
    [Key]
    public int Id { get; set; }
}

And my DbContext is like:

public class CDefContext : Microsoft.EntityFrameworkCore.DbContext
{
    public virtual Microsoft.EntityFrameworkCore.DbSet<CellDefinition> CellDefinition { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
    }
}

When I try to access the object as an entity directly, I get an error:

Invalid Object Name

but if I issue the SQL with the same object name it works properly.

// This fails with Invalid Object Name
return cDefContext.CellDefinition.ToList();

// This succeeds
return cDefContext.CellDefinition.FromSql("select * from CDef.CellDefinition").ToList()
1 Answers

I found the solution. You can't put the schema in the table name.

//This Does NOT work
[Table("Cdef.CellDefinition")]
public partial class CellDefinition{}


//But this DOES work
[Table("CellDefinition",Schema = "Cdef")]
public partial class CellDefinition{}
Related