Npsql.EntityFramework7无法使用npgsql服务器
本文关键字:npgsql 服务器 EntityFramework7 Npsql | 更新日期: 2023-09-27 17:59:54
我对C#还很陌生。我在下面的.UseNpgsql(string connectionString)
上看到了一些红色的歪歪扭扭(错误下划线)。悬停错误告诉我可能没有使用正确的using语句。
using Microsoft.Data.Entity;
namespace Something.Context {
public class OauthTokenContext : DbContext
{
public DbSet<Model.OauthToken> OauthTokens { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder builder)
{
var connectionString = @"Server=localhost; Port=1337; User Id=tinganho; Password=secret; Database=hello";
builder.UseNpgsql(connectionString);
}
}
}
在我的project.json
中,我有以下依赖项:
"dependencies": {
"Npgsql.EntityFramework7": "3.1.0-unstable0038",
"Npgsql": "3.1.0-unstable0038"
}
并且在startup.cs
:中
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Hosting;
using Microsoft.AspNet.Http;
using Microsoft.Framework.ConfigurationModel;
using Microsoft.AspNet.Routing;
using System.Linq;
using Microsoft.Data.Entity;
using Microsoft.Framework.DependencyInjection;
using Npgsql;
using Npgsql.EntityFramework7;
using Something.Context;
using Something.Model;
namespace Something
{
public class Startup
{
public Startup(IHostingEnvironment env)
{
}
// This method gets called by a runtime.
// Use this method to add services to the container
public void ConfigureServices(IServiceCollection services)
{
services.AddEntityFramework()
.AddDbContext<OauthTokenContext>();
services.AddMvc();
// Uncomment the following line to add Web API services which makes it easier to port Web API 2 controllers.
// You will also need to add the Microsoft.AspNet.Mvc.WebApiCompatShim package to the 'dependencies' section of project.json.
// services.AddWebApiConventions();
}
public IConfiguration Configuration { get; set; }
// Configure is called after ConfigureServices is called.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
// Configure the HTTP request pipeline.
app.UseStaticFiles();
// Add MVC to the request pipeline.
app.UseMvc();
// Add the following route for porting Web API 2 controllers.
// routes.MapWebApiRoute("DefaultApi", "api/{controller}/{id?}");
}
}
}
当我在services.AddEntityFramework()
之后加上.AddNpgsql()
时,我得到:
System.IO.FileNotFoundException: Could not load file or assembly 'Microsoft.Framework.DependencyInjection.Abstractions' or one of its dependencies
您应该使用这种方法:
1) 进入启动。ConfigureServices仅添加服务。AddEntityFrameworkNpgsql();
public void ConfigureServices(IServiceCollection services)
{
//...
services.AddEntityFrameworkNpgsql();
}
2) into类继承DbContext:
public class DatabaseClass : DbContext
{
//...
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseNpgsql("my connection string");
}
}