C
C#•8mo ago
Retro Afro

ASP.NET EF help

Can anyone help me with this , I dont know why 'usesqlserver' is underlined while I have entityframework installed .
No description
53 Replies
FusedQyou
FusedQyou•8mo ago
The providers have their own library, SQLServer included
FusedQyou
FusedQyou•8mo ago
Microsoft.EntityFrameworkCore.SqlServer 8.0.4
Microsoft SQL Server database provider for Entity Framework Core.
Gutti
Gutti•8mo ago
C#
public class TheBigStoreContext : DbContext
{
public TheBigStoreContext(DbContextOptions options) : base(options)
{
}

public TheBigStoreContext()
{
}
C#
public class TheBigStoreContext : DbContext
{
public TheBigStoreContext(DbContextOptions options) : base(options)
{
}

public TheBigStoreContext()
{
}
Gutti
Gutti•8mo ago
No description
Gutti
Gutti•8mo ago
I think u need Core, SqlServer, Tools for it
FusedQyou
FusedQyou•8mo ago
No, he just needs to install Microsoft.EntityFrameworkCore.SqlServer, which is what I mentioned already
Retro Afro
Retro AfroOP•8mo ago
it worked bro thank you so much
Gutti
Gutti•8mo ago
He still needs to add this constructor
C#
public AppDbContext()
{
}
C#
public AppDbContext()
{
}
Retro Afro
Retro AfroOP•8mo ago
where do i hvae to write this?
Gutti
Gutti•8mo ago
If u use migrations
Pobiega
Pobiega•8mo ago
You absolutely do not need a parameterless constructor
phi
phi•8mo ago
if you intend on using Entityframeworkcore you need to have a parameterless constructor if you wanna create migrations as far as im concerned, but if you have an alternative id like to learn from it:)
Gutti
Gutti•8mo ago
Like this my man
C#
public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
{
}

public AppDbContext()
{
}
C#
public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
{
}

public AppDbContext()
{
}
Pobiega
Pobiega•8mo ago
I use EF Core daily, and have created many migrations. You do not need a paramterless constructor for your context. you just need the options one. it even works for console apps, doesnt need to be webapi
Gutti
Gutti•8mo ago
Sounds weird because i got some issues when is was trying to add new migration without a parameterless constructor else can u try showing me how u would do it?
Pobiega
Pobiega•8mo ago
There really isnt anything to it, you just have the normal options ctor, and your app must use the generic host builder iirc and now the dotnet ef commands work just fine here is an example from a demo app I have
var builder = Host.CreateDefaultBuilder();

builder.ConfigureServices(services =>
{
services.AddDbContext<MyDbContext>(o =>
o.UseSqlServer("Data Source=.;Initial Catalog=TestDb;User Id=sa;Password=aaaAAA!!!;TrustServerCertificate=True"));

services.AddTransient<Application>();
});

builder.ConfigureLogging(x => x.AddConsole());

var host = builder.Build();

var app = host.Services.GetRequiredService<Application>();

await app.Run();
var builder = Host.CreateDefaultBuilder();

builder.ConfigureServices(services =>
{
services.AddDbContext<MyDbContext>(o =>
o.UseSqlServer("Data Source=.;Initial Catalog=TestDb;User Id=sa;Password=aaaAAA!!!;TrustServerCertificate=True"));

services.AddTransient<Application>();
});

builder.ConfigureLogging(x => x.AddConsole());

var host = builder.Build();

var app = host.Services.GetRequiredService<Application>();

await app.Run();
public class MyDbContext : DbContext
{
public MyDbContext(DbContextOptions<MyDbContext> options) : base(options)
{
}

public DbSet<Patient> Patients => Set<Patient>();

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.ApplyConfigurationsFromAssembly(typeof(MyDbContext).Assembly);
base.OnModelCreating(modelBuilder);
}
}
public class MyDbContext : DbContext
{
public MyDbContext(DbContextOptions<MyDbContext> options) : base(options)
{
}

public DbSet<Patient> Patients => Set<Patient>();

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.ApplyConfigurationsFromAssembly(typeof(MyDbContext).Assembly);
base.OnModelCreating(modelBuilder);
}
}
phi
phi•8mo ago
so in theory i would need my parameterless constructor in my dbcontext here:
public class WebshopDbContext : DbContext
{
public WebshopDbContext(DbContextOptions<WebshopDbContext> options) : base(options) { }
public WebshopDbContext()
{

}
public DbSet<Product> Products { get; set; }
public DbSet<Category> Categories { get; set; }
public DbSet<Customer> Customers { get; set; }
public DbSet<Order> Orders { get; set; }
public DbSet<OrderItem> OrderItems { get; set; }
public DbSet<User> Users { get; set; }
public DbSet<PicturePaths> Paths { get; set; }
public DbSet<UserRole> UserRoles { get; set; }
public DbSet<Roles> Roles { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
optionsBuilder.UseSqlServer("Data Source=xxxxxx;Initial Catalog=xxxxxxxx;Integrated Security=True");
optionsBuilder.EnableSensitiveDataLogging();
optionsBuilder.UseLoggerFactory(new ServiceCollection()
.AddLogging(builder => builder.AddConsole()
.AddFilter(DbLoggerCategory.Database.Command.Name, LogLevel.Information))
.BuildServiceProvider().GetService<ILoggerFactory>());
}

base.OnConfiguring(optionsBuilder);
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Customer>()
.HasOne(c => c.User)
.WithOne(u => u.Customer)
.HasForeignKey<User>(u => u.CustomerId);
modelBuilder.Entity<Customer>().HasKey(c => c.CustomerId);
modelBuilder.Entity<User>().HasKey(u => u.UserId);
}
}
public class WebshopDbContext : DbContext
{
public WebshopDbContext(DbContextOptions<WebshopDbContext> options) : base(options) { }
public WebshopDbContext()
{

}
public DbSet<Product> Products { get; set; }
public DbSet<Category> Categories { get; set; }
public DbSet<Customer> Customers { get; set; }
public DbSet<Order> Orders { get; set; }
public DbSet<OrderItem> OrderItems { get; set; }
public DbSet<User> Users { get; set; }
public DbSet<PicturePaths> Paths { get; set; }
public DbSet<UserRole> UserRoles { get; set; }
public DbSet<Roles> Roles { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
optionsBuilder.UseSqlServer("Data Source=xxxxxx;Initial Catalog=xxxxxxxx;Integrated Security=True");
optionsBuilder.EnableSensitiveDataLogging();
optionsBuilder.UseLoggerFactory(new ServiceCollection()
.AddLogging(builder => builder.AddConsole()
.AddFilter(DbLoggerCategory.Database.Command.Name, LogLevel.Information))
.BuildServiceProvider().GetService<ILoggerFactory>());
}

base.OnConfiguring(optionsBuilder);
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Customer>()
.HasOne(c => c.User)
.WithOne(u => u.Customer)
.HasForeignKey<User>(u => u.CustomerId);
modelBuilder.Entity<Customer>().HasKey(c => c.CustomerId);
modelBuilder.Entity<User>().HasKey(u => u.UserId);
}
}
Unknown User
Unknown User•8mo ago
Message Not Public
Sign In & Join Server To View
Pobiega
Pobiega•8mo ago
That is an unholy OnConfiguring
Unknown User
Unknown User•8mo ago
Message Not Public
Sign In & Join Server To View
FusedQyou
FusedQyou•8mo ago
You don't need this Oh my chat was scrolled up Completely unneeded, especially since the question was about a compiler error It would only be required when the class has to implement some generic constraint that forces it, but a context works with DI which is perfectly capable of having parameters Also, please register a proper logger instead of using UseLoggerFactory like that That setup is questionable If you just use a proper setup in the root service collection then the context will work with that by default Unless you have a specific reason for a custom system in this
phi
phi•8mo ago
my teacher made it like that haha so i just assumed it was correct
FusedQyou
FusedQyou•8mo ago
Oof, common bad teacher issue I assume you have a configured service collection you add the context to?
phi
phi•8mo ago
yeah.. hes not really much of a teacher its mostly self learning
FusedQyou
FusedQyou•8mo ago
Yeah I hear that often
phi
phi•8mo ago
😛 im not sure what you mean by this so probably not haha
FusedQyou
FusedQyou•8mo ago
Is this a web api? Do you have a startup.cs file?
phi
phi•8mo ago
blazor webassembly no
FusedQyou
FusedQyou•8mo ago
That one has it too, but if you use webassembly then you also need a server Otherwise you have a client application that communicates with a database, which makes no sense So now I'm confused
phi
phi•8mo ago
ill show you my solution
phi
phi•8mo ago
No description
FusedQyou
FusedQyou•8mo ago
So you do have an API
phi
phi•8mo ago
yeah
FusedQyou
FusedQyou•8mo ago
Surely the context has to work for the API then? Can you expand the API?
phi
phi•8mo ago
No description
FusedQyou
FusedQyou•8mo ago
Ok you use a minimal API then In Program.cs you set up the service collection That's where you have AddDbContext<>();
phi
phi•8mo ago
oh you meant lke that haha
builder.Services.AddScoped<ICategoryService, CategoryService>();
builder.Services.AddScoped<IProductService, ProductService>();
builder.Services.AddScoped<IOrderService, OrderService>();
builder.Services.AddScoped<IUserServices, UserServices>();
builder.Services.AddScoped<IUserRepository, UserRepository>();

builder.Services.AddControllers().AddNewtonsoftJson();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

builder.Services.AddDbContext<WebshopDbContext>(options => options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}

app.UseHttpsRedirection();
app.UseAuthorization();

app.MapControllers();

app.Run();
builder.Services.AddScoped<ICategoryService, CategoryService>();
builder.Services.AddScoped<IProductService, ProductService>();
builder.Services.AddScoped<IOrderService, OrderService>();
builder.Services.AddScoped<IUserServices, UserServices>();
builder.Services.AddScoped<IUserRepository, UserRepository>();

builder.Services.AddControllers().AddNewtonsoftJson();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

builder.Services.AddDbContext<WebshopDbContext>(options => options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}

app.UseHttpsRedirection();
app.UseAuthorization();

app.MapControllers();

app.Run();
FusedQyou
FusedQyou•8mo ago
In there you can just set up a proper logger, using Serilog for example, and the context will use that by default
phi
phi•8mo ago
ill look into it
FusedQyou
FusedQyou•8mo ago
var logger = new LoggerConfiguration()
.ReadFrom.Configuration(builder.Configuration)
.CreateLogger();

// Static logger for developmental purposes or where DI is not accessible. Use the injected ILogger for anything else.
Log.Logger = logger;

try
{
// Provide Serilog as the main logger.
_ = builder.Logging.ClearProviders();
_ = builder.Services.AddLogging(builder => builder.AddSerilog(logger));

...
}
catch (Exception ex)
{
logger.Error(ex, "Error during initial builder setup.");
return;
}
var logger = new LoggerConfiguration()
.ReadFrom.Configuration(builder.Configuration)
.CreateLogger();

// Static logger for developmental purposes or where DI is not accessible. Use the injected ILogger for anything else.
Log.Logger = logger;

try
{
// Provide Serilog as the main logger.
_ = builder.Logging.ClearProviders();
_ = builder.Services.AddLogging(builder => builder.AddSerilog(logger));

...
}
catch (Exception ex)
{
logger.Error(ex, "Error during initial builder setup.");
return;
}
This is my Serilog setup for a site I am hosting
Gutti
Gutti•8mo ago
C#
using var logger = new LoggerConfiguration()
.WriteTo.Console()
.WriteTo.File("Logs/log.txt", rollingInterval: RollingInterval.Day)
.CreateLogger();

builder.Logging.ClearProviders();

builder.Logging.AddSerilog(logger);
C#
using var logger = new LoggerConfiguration()
.WriteTo.Console()
.WriteTo.File("Logs/log.txt", rollingInterval: RollingInterval.Day)
.CreateLogger();

builder.Logging.ClearProviders();

builder.Logging.AddSerilog(logger);
FusedQyou
FusedQyou•8mo ago
Then my database context is just this
/// <inheritdoc/>
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
base.OnConfiguring(optionsBuilder);
ArgumentNullException.ThrowIfNull(optionsBuilder, nameof(optionsBuilder));

if (optionsBuilder.IsConfigured)
{
return;
}

...

// Log anything to our logger.
_ = optionsBuilder.LogTo(message => this._logger.LogDebug(message));
}
/// <inheritdoc/>
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
base.OnConfiguring(optionsBuilder);
ArgumentNullException.ThrowIfNull(optionsBuilder, nameof(optionsBuilder));

if (optionsBuilder.IsConfigured)
{
return;
}

...

// Log anything to our logger.
_ = optionsBuilder.LogTo(message => this._logger.LogDebug(message));
}
Gutti
Gutti•8mo ago
Like this?
Unknown User
Unknown User•8mo ago
Message Not Public
Sign In & Join Server To View
phi
phi•8mo ago
logging to txt file :PP
FusedQyou
FusedQyou•8mo ago
But even this is completely optional How come? I didn't realize that
Unknown User
Unknown User•8mo ago
Message Not Public
Sign In & Join Server To View
FusedQyou
FusedQyou•8mo ago
Good one. Would there be a way to provide a logger without it?
Unknown User
Unknown User•8mo ago
Message Not Public
Sign In & Join Server To View
FusedQyou
FusedQyou•8mo ago
Pretty sure this was required for the logger to be picked up. Otherwise it didn't work or would overlap with another one or something, but it has been a while since I even looked into that Could be wrong
Unknown User
Unknown User•8mo ago
Message Not Public
Sign In & Join Server To View
FusedQyou
FusedQyou•8mo ago
I believe that was my reason yes
Unknown User
Unknown User•8mo ago
Message Not Public
Sign In & Join Server To View
Want results from more Discord servers?
Add your server