asp.net mvc - mvc 6 ef7 Customer table object is null in AppDbContext - there is data in the database -
when enter url localhost:xxx/api/customers, showed "is null". looked @ variable in debugger mode, show table customers object null;
remember there data in table. idea?
customer class
public class customer { public string id { get; set; } public string lname { get; set; } } appsettings.json
{ "data": { "defaultconnection": { "connectionstring": "server=.\\sqlexpress;database=ef7;trusted_connection=true;" } } appdbcontext
public class appdbcontext : dbcontext { public dbset<customer> customers; protected override void onmodelcreating(modelbuilder builder) { builder.entity<customer>().haskey(c => c.id); base.onmodelcreating(builder); } } customerscontroller
[route("api/[controller]")] public class customerscontroller : controller { appdbcontext _ctx { get; set; } public customerscontroller([fromservices] appdbcontext ctx) { _ctx = ctx; } // get: api/values [httpget] public jsonresult get() { if(_ctx.customers!=null) return json(_ctx.customers.tolist()); else { return json("is null"); } } } startup.cs
public class startup { iconfigurationroot configuration; public startup(ihostingenvironment env) { var builder = new configurationbuilder() .addjsonfile("appsettings.json") .addjsonfile($"appsettings.{env.environmentname}.json", optional: true) .addenvironmentvariables(); configuration = builder.build(); } public void configureservices(iservicecollection services) { services.addmvc(); services.addentityframework().addsqlserver().adddbcontext<appdbcontext>(o=>o.usesqlserver(configuration["data:defaultconnection:connectionstring"])); } // method gets called runtime. use method configure http request pipeline. public void configure(iapplicationbuilder app) { app.useiisplatformhandler(); app.usemvc(); } // entry point application. public static void main(string[] args) => webapplication.run<startup>(args); }
never mind, dbset field instead of property. changed dbset customer {get;set}
Comments
Post a Comment