I want to make the work with data in a class library with asp.net core 1. I created MyDbContext
in a class library:
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);
}
}
My project.json
in class library:
{
"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": {
}
}
And updated startup.cs
in web application:
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);
}
My 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"
}
}
Now I want to make the migration to create the database. Using commands in cmd
dnvm use 1.0.0-rc1-final
dnx ef migrations add MyFirstMigration
dnx ef database update
First, all performed well, the database was created, but does not create a table, database is empty. If i added this code:
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);
}
The recommended approach is to leave the connection string in the AddDbContext<TContext>()
call in the application's Startup.cs and to use MigrationsAssembly()
to tell EF where the migrations will be located (which should probably be alongside the DbContext). E.g.:
services.AddEntityFramework().AddDbContext<MyDbContext>(options => options
.UseSqlServer(connectionString)
.MigrationsAssembly(assemblyName));