首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >带有EF的.Net核心网络API

带有EF的.Net核心网络API
EN

Stack Overflow用户
提问于 2017-01-12 10:00:50
回答 3查看 1.2K关注 0票数 1

我对.Net核心和实体框架都是全新的。我正在努力学习这两种技术,通过一些教程,但我正在挣扎。我的Web项目有两个控制器--向导生成的ValuesController.cs是在创建新的Core项目时创建的,另一个是我添加的名为FilesController.cs的控制器。

我的appsettings.json:

代码语言:javascript
复制
{
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Debug",
      "System": "Information",
      "Microsoft": "Information"
    }
  },

  "ConnectionStrings": {
    "    \"PropWorxConnection\"": "server=a.b.com;user id=propworx;persistsecurityinfo=True;database=abcde;password=12345"
  }
}

我的Startup.cs

代码语言:javascript
复制
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();
        }
    }
}

一个简单的模型:

代码语言:javascript
复制
namespace PropWorxAPI.Models
{
    [Table("files")]
    public partial class File
    {
        public int ID { get; set; }
        public string FileNum { get; set; }
    }
}

我的背景:

代码语言:javascript
复制
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);
        }
    }
}

我的控制器:

代码语言:javascript
复制
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!!!";
        }
    }
}

现在,当我运行它(F5)时,它会打开Edge并转到http://localhost:51932/api/values。这将显示此输出:

"value1","value2"

所以它默认为ValuesController (我如何改变它?)。无论如何,重要的是自动生成的ValuesController工作。现在,我手动将URL更改为指向我创建的FilesController,即

http://localhost:51932/api/files

...and我明白了:

HTTP 500错误这很奇怪..。该网站无法显示此页面

现在,如果我从我的FilesController中删除上下文参数--也就是说,我从:

代码语言:javascript
复制
public FilesController(PropWorxDbContext context)
        {
            _context = context;
        }

代码语言:javascript
复制
public FilesController()
        {
        }

然后它就工作了,并正确地显示:

这是文件控制器

知道为什么吗?谢谢,很抱歉这篇文章太冗长了.

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2017-01-12 10:34:43

OnConfiguring方法中删除这两行。

代码语言:javascript
复制
optionsBuilder.UseMySQL(_connectionString);
base.OnConfiguring(optionsBuilder);

您已经在ConfigureServices方法中告诉startup.cs提供程序了

代码语言:javascript
复制
services.AddDbContext<Models.PropWorxDbContext>(options =>
options.UseMySQL(Configuration.GetConnectionString("PropWorxConnection")));

更新的DbContext

代码语言:javascript
复制
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
    {

        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)
        {

        }
    }
}
票数 2
EN

Stack Overflow用户

发布于 2017-01-12 11:19:45

你的依赖注入不起作用。当框架试图创建一个新的FilesController时,它不能这样做,因为它不知道PropWorxContext是什么。

代码语言:javascript
复制
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);
        //}
    }
}

您不需要连接字符串或OnConfiguring覆盖,因为您正在Startup.cs中执行这些操作

代码语言:javascript
复制
public void ConfigureServices(IServiceCollection services)
{
    // This must come before MVC
    services.AddDbContext<Models.PropWorxDbContext>(options => options.UseMySQL(Configuration.GetConnectionString("PropWorxConnection")));

    services.AddMvc();

}

services.AddDbContext行使用依赖项注入注册数据库。它使控制器能够使用正确的构造函数工作。

代码语言:javascript
复制
public FilesController(PropWorxDbContext context)
{
    _context = context;
}

我认为您所遇到的唯一问题是DbContext中不必要的代码,这将防止依赖注入容器对其进行升级。

票数 2
EN

Stack Overflow用户

发布于 2017-01-13 13:25:46

弄明白了--我的ConnectionStrings in appsettings.json格式不正确(我有一些奇怪的正斜杠--不知道为什么.感谢你的帮助,虽然阿玛尔和user1900799 -真正的感谢!

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41610129

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档