我正在開始使用EF內核的新項目。 我有一個MSSQL服務器上的現有數據庫,我運行此命令以包含其EF結構。SqlException:無效的對象名稱
Scaffold-DbContext "Server={My Server};Database={My DB};Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer
這已經創造了我的模型類,如:
public partial class Cameras
{
public int CameraId { get; set; }
public string Description { get; set; }
}
和下面的上下文類:
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)");
});
}
}
我有4層,在我的解決方案:
- BusinessLogic
- DAL
- 接口(依賴注入)
- API(控制器)
這裏是流動的樣子在我的代碼:
Controller類
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類
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類(嘗試,並按照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();
}
和啓動類ConfigureServices方法
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<SetupToolContext>(options => options.UseSqlServer(Configuration.GetConnectionString("SQLServerConnection")));
services.AddMvc();
services.AddScoped<ICameraRepository, CamerasRepository>();
}
的問題是,我得到一個錯誤:"Invalid object name 'Cameras'."
數據庫中表的名稱是什麼?它是「相機」嗎? – silkfire
名稱是「相機」。它是由'Scaffold-DbContext'命令自動生成的。 –
攝像頭的名稱是由EF自動生成的,但表名是什麼?只是爲了確認..是相機嗎?因爲這似乎是問題所在。 – jpgrassi