Quantcast
Channel: ASP.NET Core
Viewing all articles
Browse latest Browse all 9386

.Net Core Web API with EF Core

$
0
0

am brand new to both .Net Core and to Entity Framework. I am trying to learn both technologies, by following some tutorial, but I am struggling. My Web API project has two controllers - the wizard generatedValuesController.cs that gets created when creating a new Core Web API project, and a second controller I added calledFilesController.cs.

<div>

My appsettings.json:

</div> <div>
    {      "Logging":{        "IncludeScopes":false,        "LogLevel":{          "Default":"Debug",          "System":"Information",          "Microsoft":"Information"        }      },         "ConnectionStrings":{        "    \"PropWorxConnection\"":"server=test.propworx.co.za;user id=abcde;persistsecurityinfo=True;database=josetest;password=12345"      }    }

My Startup.cs 

</div>
usingMicrosoft.AspNetCore.Builder;    usingMicrosoft.AspNetCore.Hosting;    usingMicrosoft.Extensions.Configuration;    usingMicrosoft.Extensions.DependencyInjection;    usingMicrosoft.Extensions.Logging;    usingMySQL.Data.EntityFrameworkCore.Extensions;       namespacePropWorxAPI    {        publicclassStartup        {            publicStartup(IHostingEnvironment env)            {                var builder =newConfigurationBuilder()                    .SetBasePath(env.ContentRootPath)                    .AddJsonFile("appsettings.json", optional:true, reloadOnChange:true)                    .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional:true)                    .AddEnvironmentVariables();                Configuration= builder.Build();            }               publicIConfigurationRootConfiguration{get;}               publicvoidConfigureServices(IServiceCollection services)            {                services.AddMvc();                services.AddDbContext<Models.PropWorxDbContext>(options =>                    options.UseMySQL(Configuration.GetConnectionString("PropWorxConnection")));            }               publicvoidConfigure(IApplicationBuilder app,IHostingEnvironment env,ILoggerFactory loggerFactory)            {                loggerFactory.AddConsole(Configuration.GetSection("Logging"));                loggerFactory.AddDebug();                   app.UseMvc();            }        }    }

A simple model:

namespacePropWorxAPI.Models    {        [Table("files")]        publicpartialclassFile        {            publicint ID {get;set;}            publicstringFileNum{get;set;}        }    }

My Context:

usingSystem;    usingSystem.Collections.Generic;    usingSystem.Linq;    usingSystem.Threading.Tasks;    usingMicrosoft.EntityFrameworkCore;    usingMySQL.Data.EntityFrameworkCore.Extensions;       namespacePropWorxAPI.Models    {        publicclassPropWorxDbContext:DbContext        {            privatereadonlystring _connectionString;               publicPropWorxDbContext(string connectionString)            {                _connectionString = connectionString;            }               publicPropWorxDbContext(DbContextOptions<PropWorxDbContext> options):base(options)            {            }               publicDbSet<Models.File>Files{get;set;}               protectedoverridevoidOnModelCreating(ModelBuilder modelBuilder)            {                modelBuilder.Entity<Models.File>().ToTable("Files");            }               protectedoverridevoidOnConfiguring(DbContextOptionsBuilder optionsBuilder)            {                optionsBuilder.UseMySQL(_connectionString);                base.OnConfiguring(optionsBuilder);            }        }    }
<div>

and my controller:

</div>
usingMicrosoft.AspNetCore.Mvc;    usingPropWorxAPI.Models;       namespacePropWorxAPI.Controllers    {        [Route("api/[controller]")]        publicclassFilesController:Controller        {            privatereadonlyPropWorxDbContext _context;               publicFilesController(PropWorxDbContext context)            {                _context = context;            }               [HttpGet]            publicstringGet()            {                return"Controller Working!!!";            }        }    }

Now, when I run it (F5), it opens up Edge and goes to http://localhost:51932/api/values. This displays this output:

<div>

["value1","value2"]

So it's defaulting to ValuesController (How do I changed that btw???).
Anyway, the important thing is the auto generated ValuesController works. No context is being passed to this controller...
I now manually change the URL to point to the FilesController I created, i.e.

</div> <div>http://localhost:51932/api/files</div> <div>

...and I get this:

</div> <div>HTTP 500 error
That’s odd... the website can’t display this page</div> <div>

Now, if I remove the context argument from my FilesController - i.e. I go from:

publicFilesController(PropWorxDbContext context)            {                _context = context;            }
</div> <div>

to

    publicFilesController()            {            }
</div> <div>then it works and it correctly displays:</div> <div>

this is the files controller

</div> <div>Any ideas why? It's obviously related to the constructor...
Thanks, and sorry for the overly verbose post...</div>

Viewing all articles
Browse latest Browse all 9386

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>