简体   繁体   中英

SqlException: Invalid object name

I'm getting started on a new project using EF core. I have an existing database on MSSQL server and I run this command in order to include its structure for EF.

Scaffold-DbContext "Server={My Server};Database={My DB};Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer

This has created the model classes for me, such as:

public partial class Cameras
{
    public int CameraId { get; set; }
    public string Description { get; set; }
}

and the following context class:

public partial class SetupToolContext : DbContext
{
    public virtual DbSet<Cameras> Cameras { get; set; }

    public SetupToolContext(DbContextOptions<SetupToolContext> options) : base(options)
    { }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Cameras>(entity =>
        {
            entity.HasKey(e => e.CameraId)
                .HasName("PK_Cameras");

            entity.Property(e => e.Description).HasColumnType("varchar(500)");
        });
    }
}

I have 4 layers in my solution:

  • BusinessLogic
  • DAL
  • Interfaces (for dependency injection)
  • API (controllers)

Here is how the flow looks like in my code:

Controller class

public class ValuesController : Controller
{
    ICameraRepository cameraRepository;

    public ValuesController(ICameraRepository cameraRepository)
    {
        this.cameraRepository = cameraRepository;
    }

    [HttpGet]
    public IEnumerable<Cameras> Get()
    {
        //ERROR: "Invalid object name 'Cameras'."
        return cameraRepository.List();
    }
}

CameraRepository class

public class CamerasRepository : GenericRepository<Cameras>, ICameraRepository
{
    private readonly SetupToolContext dbContext;

    public CamerasRepository(SetupToolContext dbContext) : base(dbContext)
    {
        this.dbContext = dbContext;
    }
}

public interface ICameraRepository : IRepository<Cameras>
{ }

GenericRepository class (to try and follow the Repository Pattern )

public class GenericRepository<T> : IRepository<T> where T : class
{
    private readonly SetupToolContext dbContext;

    public GenericRepository(SetupToolContext dbContext)
    {
        this.dbContext = dbContext;
    }

    public IEnumerable<T> List()
    {
        return dbContext.Set<T>().AsEnumerable();
    }
}

public interface IRepository<T>
{
    IEnumerable<T> List();
}

And Startup class ConfigureServices method

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<SetupToolContext>(options => options.UseSqlServer(Configuration.GetConnectionString("SQLServerConnection")));
    services.AddMvc();
    services.AddScoped<ICameraRepository, CamerasRepository>();
}

The issue is that I'm getting an error: "Invalid object name 'Cameras'."

这是错误的屏幕截图 What is wrong in this process?

It's kind of embarrassing to say, but I will still post this answer in case anyone else will have the same error because of not noticing this "minor" detail. I have 2 databases and it turns out I forgot to change the database name in the connection string to the correct one. I changed it in the Scaffold-DbContext command and just forgot to also change it in the connection string...

{
  "ConnectionStrings": {
    "SQLServerConnection": "Server=localhost;Database={I had the wrong db name here};Trusted_Connection=True;"
  }
}

So changing it the correct one solved it.

I had an entirely different problem, and it came with an entirely different solution.

As I was scaffolding, I was going between different databases during my development.

here is the command I used to scaffold from my local database

dotnet ef dbcontext scaffold --data-annotations "Data Source=(local)\SQLEXPRESS;Database=WebApp_DEV;Integrated Security=True" Microsoft.EntityFrameworkCore.SqlServer --context-dir Data --output-dir Models --force --no-onconfiguring 

It places the Context object into the "Data" folder, and the Components into the "Models" folder.

I got rid of the "OnConfiguring" so that I could create my own in a corresponding partial.

I created a static helper function on my Program class so that I didnt have to reference the context directly every time I wanted to access the database.

多个上下文对象

My helper method used the "WebApp_MainContext" class, and my partial worked fine.... But the classes added in Dev never worked.... Frustrating me for hours.....

I tried copying it over in my script, but it requires a manual class rename..

In retrospect, trying a simple file copy was pretty dumb...

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