ASP.NET MVC & Entity Framework : keyword not supported: - c#

I can't create my Entity Framework word database in the ASP.NET MVC project; I get an error
Keyword not supported: 'database'
even if I change my database name.
How can I fix it?
It's weird because I can migrate the database but this error pops up when I try to update it
My DbContext
public class SpletneContext : DbContext
{
public DbSet<UporabnikM> Uporabniki { get; set; }
public DbSet<Glasba> Glasbe { get; set; }
public DbSet<Instrument> Instrumanti { get; set; }
public DbSet<Oseba> Oseba { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(
#"Server=(localdb)\mssqllocaldb;DinamicneSpletne=C;Trusted_Connection=True");
}
}

It seems that your connection string is incorrect, it should look like this:
"Data Source=(localdb)\mssqllocaldb;Initial Catalog=YOUR_DATABASE_NAME;Trusted_Connection=True;

Looks like your connection string not correct format. Might it because of "\" this.
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(
#"Server=(localdb)mssqllocaldb;DinamicneSpletne=C;Trusted_Connection=True");
}

Related

MAUI 'SQLite Error 1: 'no such table: Players'.'

when i want to add fields in the database it tells me "SQLite Error 1: 'no such table: Players'." but as soon as i look at my database there is a players table. how can i solve this problem?
Here are the files for saving in the DB
GameDbContext
namespace MereTuBois.Data
{
public class GameDbContext : DbContext
{
private readonly IDeviceService _deviceService;
public DbSet<Players> Players { get; set; }
public DbSet<Session> Sessions { get; set; }
public GameDbContext(IDeviceService deviceService)
{
_deviceService = deviceService;
//this.Database.EnsureCreated();
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
string dbPath = Path.Combine(_deviceService?.AppDataDirectory ?? ".", "mereTubois.db3");
optionsBuilder.UseSqlite($"Filename={dbPath}");
}
}
public class HistoryContextFacotry : IDesignTimeDbContextFactory<GameDbContext>
{
public GameDbContext CreateDbContext(string[] args)
{
return new GameDbContext(null);
}
}
}
link to the migration : https://github.com/Waterlok653/MIgration
to solve the problem I have removed the following comment : this.Database.EnsureCreated();

How should I seed data in Entity Framework 6

I've problem with seeding data to database. Eariler I tried way from this tut: Seed Data in EF 6 Code-First
and then the seed method is never called
DBSchool.cs
namespace SchoolTest.DAL
{
public class DBSchool : DbContext
{
public DBSchool() : base("DBSchool")
{
Database.SetInitializer(new Seeder());
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
public DbSet<Guest> Guests { get; set; }
}
}
Seeder.cs
public class Seeder : DropCreateDatabaseAlways<DBSchool>
{
protected override void Seed(DBSchool context)
{
IList<Guest> GuestList = new List<Guest>();
GuestList.Add(new Guest()
{
Name = "Dexter",
Surname = "Dexter",
Email = "test#test.com"
});
context.Guests.AddRange(GuestList);
context.SaveChanges();
base.Seed(context);
}
}
Guest.cs
public class Guest
{
public string Name { get; set; }
public string Surname { get; set; }
public string Email { get; set; }
[Key]
public int GuestId { get; set; }
}
App.config
<appSettings>
<add key="DatabaseInitializerForType SchoolTest.DAL.DBSchool, SchoolTest"
value="SchoolTest.Data.Seeder, SchoolTest" />
</appSettings>
Is there any way to call the Seed() method or just through the Configuration.cs?
Try changing your code like this.
public class DBSchool : DbContext
{
public DBSchool() : base("name=<database-name>")
{
Database.SetInitializer<DBSchool>(new Seeder());
}
// Rest of your implementation
}
Replace <database-name> with the name of your database.
If that didn't work, you can give a Generic Type Parameter to the context class and change your code as follows.
Seeder.cs -> public class Seeder<T> : DropCreateDatabaseAlways<DBSchool>
DBSchool.cs -> Database.SetInitializer<DBSchool>(new Seeder<DBSchool>());
Read more on that here.
If that didn't work either, you can use migrations and seed data using custom sql using Sql().

System.Dynamic.Linq.Core + PostreSql call date_part function

Hi to all and Sorry for my bad English!
I'm doing some tests with Entity Framework Core 5 + Postgre + dynamic linq core
My DataContext is defined like this:
public class Context: DbContext {
public DbSet<Models.Anagrafica> Anagrafiche {get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseNpgsql(#"Host=XYZ;Database=XYZ;Username=XYZ;Password=XYZ");
base.OnConfiguring(optionsBuilder);
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Models.Anagrafica>().ToTable("Anagrafiche");
modelBuilder.Entity<Models.Anagrafica>().Property(p => p.Id)HasColumnName("id");
modelBuilder.Entity<Models.Anagrafica>().Property(p => p.RagioneSociale).HasColumnName ("ragionesociale");
modelBuilder.Entity<Models.Anagrafica>().Property(p => p.DataAttivazione).HasColumnName("dataattivazione");
base.OnModelCreating (modelBuilder);
}
}
The entity Anagrafica is defined as follows:
public class Anagrafica {
public int Id { get; set; }
public string RagioneSociale { get; set; }
public DateTime? DataAttivazione { get; set; }
}
Question:
Is it possible to use the date_part function in the where?
If I run the code
var data = context.Anagrafiche.Where("date_part(\"week\", dataattivazione) = #0",1).ToList();
I get the error message
System.Linq.Dynamic.Core.Exceptions.ParseException: 'No applicable method 'date_part' exists in type 'Anagrafica''
Is it possible to use database functions and/or UDF in Dynamic Linq?
If it is possible to do it what am I wrong?
Thanks!

Database Schema not changing at Runtime in Asp.net Core 2.2 & Entity Framework Core

i had an application where data is saved in different sql schema for different Users.
For e.g.
User 1 Data is saved in SCHEMA1
User 2 Data is saved in SCHEMA2
Previously application was developed in MVC 3 and it is working fine and as expected.
Now we are migrating application in .Net Core 2.2 in which this fucntionality is not working
.net core does not have IDbModelCacheKeyProvider due to this only one schema is working
Below is the DBContext File
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
//public string Schema { get; set; }
private readonly IConfiguration configuration;
public string SchemaName { get; set; }
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
public ApplicationDbContext(string schemaname)
: base()
{
SchemaName = schemaname;
}
public DbSet<EmployeeDetail> EmployeeDetail { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
var builder = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json");
var configuration = builder.Build();
optionsBuilder.UseSqlServer(configuration["ConnectionStrings:SchemaDBConnection"]);
var serviceProvider = new ServiceCollection().AddEntityFrameworkSqlServer()
.AddTransient<IModelCustomizer, SchemaContextCustomize>()
.BuildServiceProvider();
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.RemovePluralizingTableNameConvention();
modelBuilder.HasDefaultSchema(SchemaName);
base.OnModelCreating(modelBuilder);
}
public string CacheKey
{
get { return SchemaName; }
}
}
public class SchemaContextCustomize : ModelCustomizer
{
public SchemaContextCustomize(ModelCustomizerDependencies dependencies)
: base(dependencies)
{
}
public override void Customize(ModelBuilder modelBuilder, DbContext dbContext)
{
base.Customize(modelBuilder, dbContext);
string schemaName = (dbContext as ApplicationDbContext).SchemaName;
(dbContext as ApplicationDbContext).SchemaName = schemaName;
}
}
My question is how to change schemaName at runtime
So what is the right way to organize that mechanism:
Figure out the schema name by the user credentials;
Get user-specific data from database from specific schema.
I was able to change schema at runtime by changing onConfiguring Method
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public string SchemaName { get; set; }
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
public ApplicationDbContext(string schemaname)
: base()
{
SchemaName = schemaname;
}
public DbSet<EmployeeDetail> EmployeeDetail { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
var builder = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json");
var configuration = builder.Build();
var serviceProvider = new ServiceCollection().AddEntityFrameworkSqlServer()
.AddSingleton<IModelCustomizer, SchemaContextCustomize>()
.BuildServiceProvider();
optionsBuilder.UseSqlServer(configuration["ConnectionStrings:SchemaDBConnection"]).UseInternalServiceProvider(serviceProvider);
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
// modelBuilder.MapProduct(SchemaName);
modelBuilder.RemovePluralizingTableNameConvention();
if (!string.IsNullOrEmpty(SchemaName))
{
modelBuilder.HasDefaultSchema(SchemaName);
}
base.OnModelCreating(modelBuilder);
}
public string CacheKey
{
get { return SchemaName; }
}
public class SchemaContextCustomize : ModelCustomizer
{
public SchemaContextCustomize(ModelCustomizerDependencies dependencies)
: base(dependencies)
{
}
public override void Customize(ModelBuilder modelBuilder, DbContext dbContext)
{
base.Customize(modelBuilder, dbContext);
string schemaName = (dbContext as ApplicationDbContext).SchemaName;
(dbContext as ApplicationDbContext).SchemaName = schemaName;
}
}
}
The best way is to use Multi-Tenancy Architecture to be able to use database schema per user ( Tenant )
This architecture is recommended for Saas appllications
Concepts
Let’s agree on some basic concepts:
We use a tenant identification (or resolution) strategy to find out what tenant are we talking to
A tenant DbContext access strategy will figure out the way to retrieve (and store)
This article will show you how to implement Multi-tenancy app using .net core : https://stackify.com/writing-multitenant-asp-net-core-applications/

EF Core 2.0 Npgsql : 42P01

Im learning Postgresql with EF Core 2.0
im keep getting this error. I searched on google but but I am not able to find the right answer.
Here is some detail of my code ;
Startup.CS;
public void ConfigureServices(IServiceCollection services)
{
var connectionString = #"User ID=postgres;Password=postgres;Host=localhost;Port=5432;Database=Test;";
services.AddEntityFrameworkNpgsql()
.AddDbContext<DataContext>(options => options.UseNpgsql(connectionString));
services.AddMvc();
}
and Data Context ;
public class DataContext : DbContext
{
public DataContext(DbContextOptions<DataContext> options) : base(options)
{
}
public DbSet<Questions> Questions { get; set; }
}
and my model ;
public class Questions
{
public int Id { get; set; }
public int studentId { get; set; }
public string Title { get; set; }
public int Votes { get; set; }
}
any help would be appreciated.
Stumbled across this question and, although late to the party, I've also experienced case sensitivity with Oracle (using Oracle.EntityFrameworkCore, where I needed uppercase) and postgres (using Npgsql.EntityFrameworkCore, where I needed lowercase) for table/column names.
I'll add my resolution here so that it helps anyone else in future. I resolved by creating an extension method as follows:
public static void LowercaseRelationalTableAndPropertyNames(this ModelBuilder modelBuilder)
{
foreach (var entity in modelBuilder.Model.GetEntityTypes())
{
entity.Relational().TableName = entity.Relational().TableName.ToLowerInvariant();
foreach (var property in entity.GetProperties())
{
property.Relational().ColumnName = property.Relational().ColumnName.ToLowerInvariant();
}
}
}
and using as follows:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.LowercaseRelationalTableAndPropertyNames();
}
which allows models to be built with mixed case and converted at runtime as follows:
public class Questions
{
public int Id { get; set; }
public int StudentId { get; set; }
}
Note, for EFCore 3.0, the extension method changes as follows:
public static void LowercaseRelationalTableAndPropertyNames(this ModelBuilder modelBuilder)
{
foreach (var entity in modelBuilder.Model.GetEntityTypes())
{
entity.SetTableName(entity.GetTableName().ToLowerInvariant());
foreach (var property in entity.GetProperties())
{
property.SetColumnName(property.GetColumnName().ToLowerInvariant());
}
}
}
Alright fixed.
i think postgresql is case sensetive.
when i changed model equal to database problem is solved.
here is my new model.

Categories