Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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()
like image 942
John P Avatar asked Oct 30 '25 00:10

John P


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{}
like image 171
John P Avatar answered Nov 01 '25 07:11

John P



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!