如何在類庫中使用Entity Framework 7?

asp.net asp.net-core entity-framework-core

我想用asp.net core 1在MyDbContext中進行數據處理。我在MyDbContext中創建了MyDbContext

public class MyDbContext: DbContext
{
    public DbSet<User> Users { get; set; }
    public DbSet<UserProfile> Profiles { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
            base.OnModelCreating(modelBuilder);

            // maybe need to add foreign key
            modelBuilder.Entity<User>()
                .HasOne(p => p.Profile)
                .WithOne(u => u.User)
                .HasForeignKey<UserProfile>(p => p.UserId);
    }
}

我在類庫中的project.json

{
  "version": "1.0.0-*",
  "description": "DatabaseCore Class Library",
  "authors": [ "alex-pc" ],
  "tags": [ "" ],
  "projectUrl": "",
  "licenseUrl": "",
  "frameworks": {
    "net451": {
      "dependencies": {
        "EntityFramework.MicrosoftSqlServer": "7.0.0-rc1-final",
        "EntityFramework.Commands": "7.0.0-rc1-final"
      },
      "frameworkAssemblies": {
        "System.Runtime": "4.0.10.0",
        "System.Data.Entity": "4.0.0.0",
        "System.Data": "4.0.0.0",
        "System.ComponentModel.DataAnnotations": "4.0.0.0"
      }
    }
  },

  "dependencies": {

  }
}

並在Web應用程序中更新了startup.cs

 public class Startup
{
    public Startup(IHostingEnvironment env)
    {
        // Set up configuration sources.
        var builder = new ConfigurationBuilder()
            .AddJsonFile("appsettings.json")
            .AddEnvironmentVariables();

        if (env.IsDevelopment())
        {

            builder.AddApplicationInsightsSettings(developerMode: true);
        }
        Configuration = builder.Build();
    }

    public IConfigurationRoot Configuration { get; set; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddEntityFramework()
            .AddSqlServer()
            .AddDbContext<MyDbContext>(options =>
            {
                options.UseSqlServer(Configuration["Data:ConnectionString"]);
            });
        // Add framework services.
        services.AddApplicationInsightsTelemetry(Configuration);
        //services.AddAuthorization(options =>
        //{
        //    options.AddPolicy("API", policy =>
        //    {
        //        policy.AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme);
        //        policy.RequireAuthenticatedUser();
        //    });
        //});
        services.AddAuthentication();
        services.AddCaching();
        services.AddMvc();
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        loggerFactory.AddConsole(Configuration.GetSection("Logging"));
        loggerFactory.AddDebug();

        app.UseApplicationInsightsRequestTelemetry();

        if (env.IsDevelopment())
        {
            app.UseBrowserLink();
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
        }

        app.UseIISPlatformHandler();

        app.UseApplicationInsightsExceptionTelemetry();

        app.UseStaticFiles();
        app.UseJwtBearerAuthentication(options =>
        {
            options.AutomaticAuthenticate = true;
            options.Audience = "resource_server_1";
            options.Authority = "http://localhost:4871/";
            options.RequireHttpsMetadata = false;
            options.TokenValidationParameters.ValidateLifetime = true;
        });

        // Add a new middleware issuing tokens.
        app.UseOpenIdConnectServer(options =>
        {
            options.AllowInsecureHttp = true;
            options.AuthorizationEndpointPath = PathString.Empty;
            options.TokenEndpointPath = "/connect/token";

            options.Provider = new AuthorizationProvider();
        });

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });
    }

    // Entry point for the application.
    public static void Main(string[] args) => WebApplication.Run<Startup>(args);
}

我的appsettings.json

{
  "ApplicationInsights": {
    "InstrumentationKey": ""
  },
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Verbose",
      "System": "Information",
      "Microsoft": "Information"
    }
  },
  "Data": {
    "ConnectionString": "Data Source=DESKTOP-R3AP4AT\\SQLEXPRESS;Initial Catalog=mydb;Integrated Security=True;Connect Timeout=15;Encrypt=False;TrustServerCertificate=True;ApplicationIntent=ReadWrite;MultiSubnetFailover=False"
  }
}

現在我想進行遷移以創建數據庫。使用cmd中的命令

 dnvm use 1.0.0-rc1-final
 dnx ef migrations add MyFirstMigration
 dnx ef database update

首先,所有表現都很好,數據庫是創建的,但是沒有創建表,數據庫是空的。如果我添加此代碼:

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseSqlServer(
                @"Data Source=DESKTOP-R3AP4AT\\SQLEXPRESS;Initial Catalog=mydb;Integrated Security=True;Connect Timeout=15;Encrypt=False;TrustServerCertificate=True;ApplicationIntent=ReadWrite;MultiSubnetFailover=False");
            base.OnConfiguring(optionsBuilder);
        }

錯誤 - 實例崩潰 ,結果: cmd結果

熱門答案

建議的方法是將連接字符串保留在應用程序的Startup.cs中的AddDbContext<TContext>()調用中,並使用MigrationsAssembly()告知EF遷移的位置(可能與DbContext一起)。例如:

services.AddEntityFramework().AddDbContext<MyDbContext>(options => options
    .UseSqlServer(connectionString)
    .MigrationsAssembly(assemblyName));


Related

許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow
這個KB合法嗎? 是的,了解原因
許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow
這個KB合法嗎? 是的,了解原因