Hi i am having some trouble pulling data from an existing database in Using Entity Framework 7 MVC 6. (I have posted the project code Here). I have set up appsettings.json with the proper connection string:
"Data": {
"DefaultConnection": {
"ConnectionString": "Data Source=localhost;Initial Catalog=Demo;Integrated Security=True"
}
I have my custom context:
public class DatabaseContext : DbContext
{
public DbSet<User> Users { get; set; }
public DbSet<Customer> Customers { get; set; }
}
Two Poco classes:
[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; }
}
And i am setting up the service in 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);
}
My users controller:
[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();
}
}
i keep getting the following error on the List line when I navigate to the Users/index page:
$exception {"Object reference not set to an instance of an object."} System.NullReferenceException
For some reason it is not pulling the information from the database. I create it in Microsoft SQLServer 2014. And there is data in the users table. Am i missing a step or am I trying to access the data the wrong way?
[FromServices]to the parameterDatabaseContext. You can usepublic UsersController([FromServices] DatabaseContext context)or just modifypublic IActionResult Index()topublic IActionResult Index([FromServices] DatabaseContext _context)without the usage of property_context. I don't recommend to use[FromServices]attribute to the property because the feature is dropped in RC2. If you use it then you should remove the constructor, which set_contextexplicitly. Se the answerhttp://localhost:14487/users/index/then I get the errorSqlException: Cannot open database "Demo" requested by the login. I can see that the constructorpublic UsersController([FromServices] DatabaseContext context)will be successfully called before inside ofpublic IActionResult Index()one have_contextwhich is not null.UsersControllercontroller and inside ofIndexof the controller? You can modify the launch URL fromhttp://localhost:14487/tohttp://localhost:14487/users/index/or to open the URL directly after starting the program. Is_contextnotnullnow? If you have some error then which one? I get the error during the attempt to open the databaseDemowhich I have not (noNullReferenceExceptionexception!). I didn't made any modification of the program.CustomerInfo,UserInfoandVendorInfo(the usage ofIdinstead ofid) and changingUsernameproperty ofUserclass toUserNameI get the error which you described. I can see that it will be executed correct SQL selectSELECT [u].[Id], [u].[Active], [u].[Created], [u].[EmailAddress], [u].[FirstName], [u].[LastName], [u].[Password], [u].[Updated], [u].[UserName] FROM [Users] AS [u]on the SQL server, but you get error in EF. I'm a little busy now with New Year, but I will solve the problem later and will post my answer."EntityFramework.Core": "7.0.0-rc1-final"to"EntityFramework.MicrosoftSqlServer": "7.0.0-rc1-final"inBestroproject if you would generate the entity classes usingdnx ef dbcontext scaffold ...