none
.Net Core Web API with EF

    Question

  • I 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 generated ValuesController.cs that gets created when creating a new Core Web API project, and a second controller I added called FilesController.cs.

    My appsettings.json:

        {
          "Logging": {
            "IncludeScopes": false,
            "LogLevel": {
              "Default": "Debug",
              "System": "Information",
              "Microsoft": "Information"
            }
          },
        
          "ConnectionStrings": {
            "    \"PropWorxConnection\"": "server=mysql3.propworx.co.za;user id=propworx;persistsecurityinfo=True;database=josetest;password=_#Fjls1680#_"
          }
        }

    My Startup.cs

     
    using Microsoft.AspNetCore.Builder;
        using Microsoft.AspNetCore.Hosting;
        using Microsoft.Extensions.Configuration;
        using Microsoft.Extensions.DependencyInjection;
        using Microsoft.Extensions.Logging;
        using MySQL.Data.EntityFrameworkCore.Extensions;
        
        namespace PropWorxAPI
        {
            public class Startup
            {
                public Startup(IHostingEnvironment env)
                {
                    var builder = new ConfigurationBuilder()
                        .SetBasePath(env.ContentRootPath)
                        .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                        .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
                        .AddEnvironmentVariables();
                    Configuration = builder.Build();
                }
        
                public IConfigurationRoot Configuration { get; }
        
                public void ConfigureServices(IServiceCollection services)
                {
                    services.AddMvc();
                    services.AddDbContext<Models.PropWorxDbContext>(options =>
                        options.UseMySQL(Configuration.GetConnectionString("PropWorxConnection")));
                }
        
                public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
                {
                    loggerFactory.AddConsole(Configuration.GetSection("Logging"));
                    loggerFactory.AddDebug();
        
                    app.UseMvc();
                }
            }
        }


    A simple model:

    namespace PropWorxAPI.Models
        {
            [Table("files")]
            public partial class File
            {
                public int ID { get; set; }
                public string FileNum { get; set; }
            }
        }


    My Context:

     using System;
        using System.Collections.Generic;
        using System.Linq;
        using System.Threading.Tasks;
        using Microsoft.EntityFrameworkCore;
        using MySQL.Data.EntityFrameworkCore.Extensions;
        
        namespace PropWorxAPI.Models
        {
            public class PropWorxDbContext : DbContext
            {
                private readonly string _connectionString;
        
                public PropWorxDbContext(string connectionString)
                {
                    _connectionString = connectionString;
                }
        
                public PropWorxDbContext(DbContextOptions<PropWorxDbContext> options) : base(options)
                {
                }
        
                public DbSet<Models.File> Files { get; set; }
        
                protected override void OnModelCreating(ModelBuilder modelBuilder)
                {
                    modelBuilder.Entity<Models.File>().ToTable("Files");
                }
        
                protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
                {
                    optionsBuilder.UseMySQL(_connectionString);
                    base.OnConfiguring(optionsBuilder);
                }
            }
        }

    and my controller:

     using Microsoft.AspNetCore.Mvc;
        using PropWorxAPI.Models;
        
        namespace PropWorxAPI.Controllers
        {
            [Route("api/[controller]")]
            public class FilesController : Controller
            {
                private readonly PropWorxDbContext _context;
        
                public FilesController(PropWorxDbContext context)
                {
                    _context = context;
                }
        
                [HttpGet]
                public string Get()
                {
                    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:

    ["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.

    http://localhost:51932/api/files

    ...and I get this:

    HTTP 500 error
    That’s odd... the website can’t display this page

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

    public FilesController(PropWorxDbContext context)
                {
                    _context = context;
                }

    to

        public FilesController()
                {
                }
    then it works and it correctly displays:

    this is the files controller

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

    Fabricio Rodriguez - Pretoria, South Africa


    • Edited by Fabs1977 Thursday, January 12, 2017 10:12 AM
    • Moved by Sabah ShariqMVP Thursday, January 12, 2017 10:39 AM Related to ASP.Net
    Thursday, January 12, 2017 10:08 AM

All replies

  • Hi Fabs,

    This is Visual C# forum. As your issue is related to Web, please ask your question into ASP.Net forum for getting quick response. I am moving your thread to off-topic.

    https://forums.asp.net/

    Your understanding and cooperation will be grateful.

    Thanks,
    Sabah Shariq

    [If a post helps to resolve your issue, please click the "Mark as Answer" of that post or click Answered "Vote as helpful" button of that post. By marking a post as Answered or Helpful, you help others find the answer faster. ]

    Thursday, January 12, 2017 10:39 AM
  • Thanks Sabah

    Fabricio Rodriguez - Pretoria, South Africa

    Thursday, January 12, 2017 12:55 PM