I tried to create a new Database using dotnet ef migrations add InitialCreate --context Sooziales_NetzwerkDbContext
and got this error: Unable to create an object of type ‘Sooziales_NetzwerkDbContext’. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728. The Build is successful, but than it fails with that error message. I use Sqlite for my databases. Here is my code:
Sooziales_NetzwerkDbContext:
using Microsoft.EntityFrameworkCore;
using Sooziales_Netzwerk.Models;
namespace Sooziales_Netzwerk.Data{
public class Sooziales_NetzwerkDbContext : DbContext
{
public Sooziales_NetzwerkDbContext(DbContextOptions<Sooziales_NetzwerkDbContext> options)
: base(options)
{
}
public DbSet<Link> Link {get; set;}
}
}
Link.cs:
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace Sooziales_Netzwerk.Models;
public class Link{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int idLink {get; set;}
[Display(Name = "Enter Link")]
[Required(ErrorMessage = "Upload without a link make no sence")]
public string link {get; set;}
[Display(Name = "Enter Username")]
[Required(ErrorMessage = "Upload without a link make no sence")]
public string username {get; set;}
[Display(Name = "Enter Likes")]
[Required(ErrorMessage = "Upload without a link make no sence")]
public int likes {get; set;}
}
Program.cs:
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Sooziales_Netzwerk.Data;
var builder = WebApplication.CreateBuilder(args);
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
builder.Services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlite(connectionString));
builder.Services.AddDatabaseDeveloperPageExceptionFilter();
builder.Services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
.AddEntityFrameworkStores<ApplicationDbContext>();
builder.Services.AddControllersWithViews();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseMigrationsEndPoint();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.MapRazorPages();
app.Run();
2
Answers
Add this to Program.cs:
And this to appsettings.json:
1.add below code code in Program.cs :
added a connection string to the appsettings.json file in
"ConnectionStrings"
: like below: