【发布时间】:2015-12-31 19:27:57
【问题描述】:
您好,我在 Using Entity Framework 7 MVC 6 中从现有数据库中提取数据时遇到了一些问题。(我已发布项目代码 Here)。我已经使用正确的连接字符串设置了 appsettings.json:
"Data": {
"DefaultConnection": {
"ConnectionString": "Data Source=localhost;Initial Catalog=Demo;Integrated Security=True"
}
我有我的自定义上下文:
public class DatabaseContext : DbContext
{
public DbSet<User> Users { get; set; }
public DbSet<Customer> Customers { get; set; }
}
两个 Poco 类:
[Table("Customers")]
public class Customer
{
[Key]
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Username { get; set; }
public string Password { get; set; }
public string EmailAddress { get; set; }
public DateTime Created { get; set; }
public DateTime Updated { get; set; }
public User User { get; set; }
public bool Active { get; set; }
}
[Table("Users")]
public class User
{
[Key]
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Username { get; set; }
public string Password { get; set; }
public string EmailAddress { get; set; }
public DateTime Created { get; set; }
public DateTime Updated { get; set; }
public bool Active { get; set; }
}
我正在startup.cs中设置服务
public Startup(IHostingEnvironment env)
{
// Set up configuration sources.
var builder = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);
if (env.IsDevelopment())
{
// For more details on using the user secret store see http://go.microsoft.com/fwlink/?LinkID=532709
builder.AddUserSecrets();
// This will push telemetry data through Application Insights pipeline faster, allowing you to view results immediately.
builder.AddApplicationInsightsSettings(developerMode: true);
}
builder.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; set; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddApplicationInsightsTelemetry(Configuration);
services.AddEntityFramework()
.AddSqlServer()
.AddDbContext<DatabaseContext>(options =>
options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"]));
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
services.AddMvc();
// Add application services.
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
app.UseApplicationInsightsRequestTelemetry();
if (env.IsDevelopment())
{
app.UseBrowserLink();
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
// For more details on creating database during deployment see http://go.microsoft.com/fwlink/?LinkID=615859
try
{
using (var serviceScope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>()
.CreateScope())
{
serviceScope.ServiceProvider.GetService<ApplicationDbContext>()
.Database.Migrate();
}
}
catch { }
}
app.UseIISPlatformHandler(options => options.AuthenticationDescriptions.Clear());
app.UseApplicationInsightsExceptionTelemetry();
app.UseStaticFiles();
app.UseIdentity();
// To configure external authentication please see http://go.microsoft.com/fwlink/?LinkID=532715
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
// Entry point for the application.
public static void Main(string[] args) => WebApplication.Run<Startup>(args);
}
我的用户控制器:
[Route("[controller]")]
public class UsersController : Controller
{
public DatabaseContext _context { get; set; }
public UsersController(DatabaseContext context)
{
_context = context;
}
[Route("[action]")]
public IActionResult Index()
{
using (_context)
{
List<User> users = _context.Users.ToList();
}
return View();
}
}
当我导航到用户/索引页面时,我在列表行上不断收到以下错误:
$exception {"对象引用未设置为对象的实例。"} System.NullReferenceException
由于某种原因,它没有从数据库中提取信息。我在 Microsoft SQLServer 2014 中创建它。用户表中有数据。我错过了一个步骤还是我试图以错误的方式访问数据?
【问题讨论】:
-
尝试将
[FromServices]添加到参数DatabaseContext。您可以使用public UsersController([FromServices] DatabaseContext context)或仅将public IActionResult Index()修改为public IActionResult Index([FromServices] DatabaseContext _context),而不使用属性_context。我不建议对属性使用[FromServices]属性,因为该功能已在 RC2 中删除。如果你使用它,那么你应该删除显式设置_context的构造函数。硒the answer -
如果我打开 URL
http://localhost:14487/users/index/,则会收到错误SqlException: Cannot open database "Demo" requested by the login。我可以看到构造函数public UsersController([FromServices] DatabaseContext context)将在public IActionResult Index()内部被成功调用,其中一个_context不为空。 -
能否在控制器的
UsersController和Index的控制器内部设置断点?您可以将启动 URL 从http://localhost:14487/修改为http://localhost:14487/users/index/或在启动程序后直接打开 URL。现在是_context不是null吗?如果你有一些错误,那是哪一个?我在尝试打开我没有打开的数据库Demo时遇到错误(没有NullReferenceException异常!)。我没有对程序进行任何修改。 -
在修复了数据库视图
CustomerInfo、UserInfo和VendorInfo中的一些小写错误之后(使用Id而不是id)并更改Username的@987654355 属性@class toUserName我得到了你描述的错误。我可以看到它将在 SQL 服务器上执行正确的 SQL selectSELECT [u].[Id], [u].[Active], [u].[Created], [u].[EmailAddress], [u].[FirstName], [u].[LastName], [u].[Password], [u].[Updated], [u].[UserName] FROM [Users] AS [u],但在 EF 中出现错误。我现在新年有点忙,但我稍后会解决问题并发布我的答案。 -
我忘了提到,如果您要使用
dnx ef dbcontext scaffold ...生成实体类,您应该在Bestro项目中将"EntityFramework.Core": "7.0.0-rc1-final"更改为"EntityFramework.MicrosoftSqlServer": "7.0.0-rc1-final"
标签: c# asp.net-core-mvc entity-framework-core