简体   繁体   中英

Invalid object name when using Entity Framework to read SQL Server table

I'm trying to set up a database connection using Entity Framework in an ASP.NET Core application, but each time I attempt to read from my data context, it fails stating that the table I'm trying to get is invalid.

I'm relatively new to EF with ASP.NET Core, so I could be missing something obvious. How can I get EF to connect/find my object?

I have my connection string as follows:

Data Source=DbServer;Initial Catalog=AIT;Integrated Security=True

And the table that I'm trying to read from is on DbServer :

AIT.processing.orderProcessing

The error I'm getting when the DB context attempts to connect is this:

SqlException: Invalid object name 'processing.orderProcessing'.

I've looked at the context itself when it runs, and it is connecting to the correct server. I've also validated that the database is correct in the connection string and that it contains the processing.orderProcessing table. I've also tried to explicitly tell EF that it should be connecting to a specific object by using the Table property on my c# class:

[Table("AIT.processing.orderProcessing")]

This just causes my error message to change to:

SqlException: Invalid object name 'AIT.processing.orderProcessing'.

As far as I know, if it is connecting to DBServer , it should be able to find that table as it definitely exists, and it is spelled correctly. I just copy/pasted it from SSMS to make sure.

Edit: The below answer was what fixed it for me. Changing my Table attribute to this:

[Table("orderProcessing", Schema = "processing")]

Caused EF to be able to connect.

So AIT is database name, processing is schema name and orderProcessing is the table name.

Try to set table name and scheme name separately using Data Annotations like:

[Table("orderProcessing", Schema = "processing")]

Or in DbContext OnModelCreating using:

 modelBuilder.Entity<MyEntity>().ToTable("orderProcessing", processing);

If your database name is "AIT" and schema is "processing" you must express EF core your schema name.

protected override void OnModelCreating(ModelBuilder builder)
{
    builder.HasDefaultSchema("processing");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM