Voglio fare il lavoro con i dati in una libreria di classi con il nucleo di asp.net 1. Ho creato MyDbContext
in una libreria di classi:
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);
}
}
Il mio project.json
nella biblioteca di classe:
{
"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": {
}
}
E startup.cs
aggiornati startup.cs
web:
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);
}
Le mie 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"
}
}
Ora voglio fare la migrazione per creare il database. Utilizzo dei comandi in cmd
dnvm use 1.0.0-rc1-final
dnx ef migrations add MyFirstMigration
dnx ef database update
Per prima cosa, tutto ha funzionato bene, il database è stato creato, ma non crea una tabella, il database è vuoto. Se ho aggiunto questo codice:
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);
}
L'approccio consigliato è di lasciare la stringa di connessione nella AddDbContext<TContext>()
nel file Startup.cs dell'applicazione e di utilizzare MigrationsAssembly()
per indicare a EF dove si troveranno le migrazioni (che probabilmente dovrebbe essere affiancato a DbContext). Per esempio:
services.AddEntityFramework().AddDbContext<MyDbContext>(options => options
.UseSqlServer(connectionString)
.MigrationsAssembly(assemblyName));