【问题标题】:Asp.net Core and Entity Framework can't connect to SQL ServerAsp.net Core 和 Entity Framework 无法连接到 SQL Server
【发布时间】:2016-09-09 15:34:00
【问题描述】:

我创建了一个 ASP.NET Core 项目和一个标识 DAL(数据访问层)的单独项目。在 DAL 项目中,我有一个非常简单的上下文。

public class AtfContext : DbContext
{
    public DbSet<Address> Addresses { get; set; }
    public DbSet<EmployeeType> EmployeeTypes { get; set; }
    public DbSet<Employee> Employees { get; set; }
}

我也会在这里定义IRepositoryRepository

public interface IRepository<T> where T : class, IEntity
{
    void Add(T entity);
    T Find(int id);
    IEnumerable<T> FindAll();
    void Delete(int id);
    void Delete(T entity);
    int Save();
}

public class Repository<T> : IRepository<T> where T : class, IEntity
{
    private AtfContext _context;

    public Repository()
    {
        _context = new AtfContext();
    }

    public void Add(T entity)
    {
        _context.Set<T>().Add(entity);
    }

    public void Delete(T entity)
    {
        _context.Set<T>().Remove(entity);
    }

    public void Delete(int id)
    {
        var entity = Find(id);
        Delete(entity);
    }

    public T Find(int id)
    {
        return _context.Set<T>().FirstOrDefault(x => x.Id == id);
    }

    public IEnumerable<T> FindAll()
    {
        return _context.Set<T>();
    }

    public int Save()
    {
        try
        {
            return _context.SaveChanges();
        }
        catch (Exception)
        {

        }
        return 0;
    }
}

我认为你不需要实体。

所以我开始构建一个不同的简单控制器

public class EmployeeController : Controller
{
    // GET: /<controller>/
    public IActionResult Index()
    {
        IRepository<Employee> repository = new Repository<Employee>();
        var employees = repository.FindAll().ToList();
        return View(employees);
    }

    public IActionResult Add()
    {
        var model = new Employee();
        return View();
    }
}

索引视图如下所示:

@model IEnumerable<Atf.DataAccess.Models.Employee>
@{
    ViewBag.Title = "Home";
}
<div id="main">
    <h2>Employees</h2>
</div>

<table>
    <tr>
        <th>First Name</th>
        <th>Last Name</th>
        <th>Phone</th>
        <th>Zip</th>
    </tr>
    @foreach (var employee in @Model)
    {
        <tr>
            <td>@employee.FirstName</td>
            <td>@employee.LastName</td>
            <td>@employee.MobilePhone</td>
            <td>@employee.Address.Zip</td>
        </tr>
    }
</table>

可能也应该显示project.json

 {
  "dependencies": {
    "Microsoft.AspNetCore.Diagnostics": "1.0.0",
    "Microsoft.AspNetCore.Server.IISIntegration": "1.0.0",
    "Microsoft.AspNetCore.Server.Kestrel": "1.0.0",
    "Microsoft.Extensions.Logging.Console": "1.0.0",
    "Microsoft.AspNetCore.StaticFiles": "1.0.0",
    "Microsoft.AspNetCore.Mvc": "1.0.0",
    "Microsoft.AspNetCore.Mvc.TagHelpers": "1.0.0",
    "EntityFramework": "6.1.3",
    "Microsoft.AspNetCore.Razor.Tools": {
      "version": "1.0.0-preview2-final",
      "type": "build"
    },
    "Microsoft.Extensions.Configuration.EnvironmentVariables": "1.0.0",
    "Microsoft.Extensions.Configuration.Json": "1.0.0",
    "Microsoft.Extensions.Logging": "1.0.0",
    "Microsoft.Extensions.Logging.Debug": "1.0.0",
    "Microsoft.Extensions.Options.ConfigurationExtensions": "1.0.0",
    "Microsoft.VisualStudio.Web.BrowserLink.Loader": "14.0.0"
  },

  "tools": {
    "BundlerMinifier.Core": "2.0.238",
    "Microsoft.AspNetCore.Razor.Tools": "1.0.0-preview2-final",
    "Microsoft.AspNetCore.Server.IISIntegration.Tools": "1.0.0-preview2-final"
  },

  "frameworks": {
    "net452": {
      "dependencies": {
        "Atf.DataAccess": {
          "target": "project"
        }
      }
    }
  },

  "buildOptions": {
    "emitEntryPoint": true,
    "preserveCompilationContext": true
  },

  "publishOptions": {
    "include": [
      "wwwroot",
      "web.config"
    ]
  },

  "scripts": {
    "postpublish": [ "dotnet publish-iis --publish-folder %publish:OutputPath% --framework %publish:FullTargetFramework%" ]
  }
}

好的,现在来解释什么是错的。我设置了一个测试项目,它是一个控制台并运行Console.WriteLine(repository.FindAll().Count()),我得到了 2 个计数。在 asp.net 核心应用程序中,我得到了 0 个显示的记录。

谁能解释一下原因?

【问题讨论】:

  • 您是否尝试过将连接字符串直接传递给 datacontext 构造函数?
  • 没有。我怎么会得到那个?我查看了 DAL 配置文件,但在那里没有看到
  • 您应该使用 Core 的依赖注入模型,它自然会提供一个点来注入连接字符串。 see here
  • 您是否尝试过使用 Intellitrace 来查看是否调用了查询或我们抛出的任何错误?

标签: c# asp.net-mvc entity-framework asp.net-core


【解决方案1】:

您需要在 Startup 中配置连接字符串,并使用依赖注入来拉入 db 上下文的实例。查看官方文档:

https://docs.efproject.net/en/latest/platforms/aspnetcore/new-db.html#register-your-context-with-dependency-injection

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-04-12
    • 2021-07-14
    • 1970-01-01
    • 2023-03-25
    • 1970-01-01
    • 1970-01-01
    • 2017-01-27
    • 2020-10-01
    相关资源
    最近更新 更多