EF Core user-defined function for PostgreSQL extension - postgresql

I currently have Sql mapped function which I want to map as a user-defined function:
context.Structures.FromSqlInterpolated($"select * from \"Structures\" where \"Molfile\" # ({search}, '')::bingo.sub")
The where method comes from a PostgreSQL extension called Bingo.
I don't understand from the docs how I should be doing that. Here's an example of the things I've tried:
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
builder.Entity<Structure>().ToTable("Structure");
builder.HasDbFunction(typeof(ChemistryContext).GetMethod(nameof(Sub), new[] { typeof(string) })).HasName("bingo.sub");
}
public IQueryable<Structure> Sub(string search)
=> FromExpression(() => Sub(search));
This particular code above fails because there's no bingo.sub user function.
Thank you for some inputs on how this should be done!

Related

Setting IsUnicode to false for all types in Entity Framework Core 6

In normal Entity Framework you could use the code
modelBuilder.Properties<string>().Configure(c => c.IsUnicode(false));
to set all created column times to a non-unicode version. I am working in EF Core 6 and trying to do this but modelBuilder does not have a Properties attribute and I am not finding any solutions that parting to EFCore 6 when searching around Has doing this universially been droped and I must specify it for every column now or is there a hidden method some where I am not seeing?
You can set all string properties to be non-unicode by default via pre-convention model configuration:
protected override void ConfigureConventions(ModelConfigurationBuilder configurationBuilder)
{
configurationBuilder.DefaultTypeMapping<string>(
b => b.HasColumnType("varchar(max)").IsUnicode(false));
}
Alternative:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
foreach (var property in modelBuilder.Model.GetEntityTypes()
.SelectMany(e => e.GetProperties()
.Where(p => p.ClrType == typeof(string))))
{
property.SetIsUnicode(false);
}
}

Ef core abstract HasQueryFilter from DbContext

I'm trying to build some generic authorize stuff ontop of DbContext so that my devs do not need to care about authorization in the repos/domain.
Simple example like
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Blog>().Property<string>("TenantId").HasField("_tenantId");
// Configure entity filters
modelBuilder.Entity<Blog>().HasQueryFilter(b => EF.Property<string>(b, "TenantId") == _tenantId);
modelBuilder.Entity<Post>().HasQueryFilter(p => !p.IsDeleted);
}
Which is MS example works. _tenantId will be used to create an expression and for each instance of DbContext it will use correct value of _tenantId.
But I do not want all our authorizen configured from our DB context, I want to inject it. Something like
public class AgreementAuthorization : IEntityAuthorization
{
private readonly string _legalEntityNumber;
public AgreementAuthorization(IAuthScope scope)
{
_legalEntityNumber = scope.LegalEntityNumber;
}
public void Build(ModelBuilder builder)
{
builder
.Entity<Agreement>()
.HasQueryFilter(a => _legalEntityNumber == null || a.LegalEntity.Number == _legalEntityNumber);
}
}
public class MyDbContext : DbContext
{
private IEnumerable<IEntityAuthorization> _entityAuthorization;
MyDbContext(IEnumerable<IEntityAuthorization> entityAuthorization)
{
_entityAuthorization = entityAuthorization;
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
builder.ApplyConfigurationsFromAssembly(typeof(MyDbContext).Assembly);
_entityAuthorization.ForEach(a => a.Build(builder));
}
}
This does not work, query willl test against null every time and pass. If I move the code directly to DbContext it will work. Meaning _entityAuthorization lies directly on DbContext.
From https://learn.microsoft.com/en-us/ef/core/querying/filters
Filters cannot contain references to navigation properties.
You are referencing navigation property LegalEntity.
And this could potentially affect you as well as you're passing in an IEnumerable<IEntityAuthorization>:
It is currently not possible to define multiple query filters on the
same entity - only the last one will be applied. However, you can
define a single filter with multiple conditions using the logical AND
operator (&& in C#).
Update:
My guess would then be that you need to reference a field/property of the MyDbContext directly and not within another object. Inject a class/interface that gives access to the values by which to filter then configure the filters at the end of the OnModelCreating method. You can interate over the entity configurations and their properties to apply the desired filter(s) based on the presence of the applicable property.

Working with Schemas in EF Code First Migrations

I suppose this question is a cosmetic one; when you initially create an EF migration, it puts the schema in by default; for example:
public override void Up()
{
DropPrimaryKey("dbo.MyTable");
AddPrimaryKey("dbo.MyTable", "NewField");
This seems fine, unit you see the key name that it generates as a result (it has dbo in the key name).
I realise that one way around this is to specify the key name directly. Are there any other options, for example, can the schema be specified for a block, but not included in the specific modifications? For example:
public override void Up()
{
UseSchema("dbo");
DropPrimaryKey("MyTable");
AddPrimaryKey("MyTable", "NewField");
I realise that you can simply omit the schema name; i.e., this will work:
public override void Up()
{
DropPrimaryKey("MyTable");
AddPrimaryKey("MyTable", "NewField");
But how would I then deal with a situation where there were more than a single schema?
You can specify default schema using HasDefaultSchema method on DbModelBuilder class instance.
modelBuilder.HasDefaultSchema("schemaName");
You can also set schema for each entity using ToTable method on EntityTypeConfiguration<TEntityType> class instance. Which will generate migration scripts with provided schema for desired entity/ies.
modelBuilder.Entity<TEntity>().ToTable("tableName", "schemaName")
You can also use Table attribute to set schema for entity.
[Table("tableName","schemaName")]
Or you can write your own custom convention
public class DynamicSchemaConvention : Convention
{
public CustomSchemaConvention()
{
Types().Configure(c => c.ToTable(c.ClrType.Name, c.ClrType.Namespace.Substring(c.ClrType.Namespace.LastIndexOf('.') + 1)));
}
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Add(new CustomSchemaConvention());
}
Related links:
DbModelBuilder.HasDefaultSchema Method
EntityTypeConfiguration.ToTable Method
TableAttribute Class
Entity Framework 6 - Code First: table schema from classes' namespace
Entity Framework Custom Code First Conventions (EF6 onwards)

How change tables's schema of Identity Server 4?

By default the tables's schema of Identity Server 4 is dbo, i want change it to security, so i create ConfigurationContext which inherit from ConfigurationDbContext:
public class ConfigurationContext : ConfigurationDbContext
{
public ConfigurationContext(DbContextOptions<ConfigurationDbContext> options, ConfigurationStoreOptions storeOptions) : base(options, storeOptions)
{ }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.HasDefaultSchema("Security");
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
var relationalOptions = RelationalOptionsExtension.Extract(optionsBuilder.Options);
relationalOptions.MigrationsHistoryTableSchema = "Security";
}
}
and in add-migration i use ConfigurationContext :
Add-Migration -c ConfigurationContext
but i got this error:
No parameterless constructor was found on 'ConfigurationContext'. Either add a parameterless constructor to 'ConfigurationContext' or add an implementation of 'IDbContextFactory' in the same assembly as 'ConfigurationContext'.
what is the problem?
IdentityServer4 provides this option. In ConfigureServices,
services.AddIdentityServer()
.AddOperationalStore(builder => builder.UseSqlServer(cnStr, options =>
options.MigrationsAssembly(migAssembly)),
storeOption => storeOption.DefaultSchema = "security")
This way, you can continue to use the IDbContextFactory as suggested in the quickstarts.
I know this is quite an old question, but I recently had a similar issue; June Lau's answer does provide some of the info you need to resolve this, but the important part is that migrations don't inspect the database context at runtime, so you need to define the schema before you create your database migration.
Don't worry about extending ConfigurationDbContext either, as that's not needed, just add something like this to your ConfigureServices method in Startup.cs:
var identityServerBuilder = services.AddIdentityServer(options =>
{
// ...
});
var migrationsAssembly = typeof(Startup).GetTypeInfo().Assembly.GetName().Name;
identityServerBuilder.AddConfigurationStore(options =>
{
options.DefaultSchema = "config";
options.ConfigureDbContext = b => b.UseSqlServer(connectionString, sql => sql.MigrationsAssembly(migrationsAssembly));
});
Once you've added that code, create a migration for the relevant database context:
Add-Migration CreateInitialSchema -Context ConfigurationDbContext
You should see that the created migration starts like this:
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.EnsureSchema(
name: "config");
migrationBuilder.CreateTable(
name: "ApiResources",
schema: "config",
columns: table => new ...
The problem is that Add-Migration -c ConfigurationContext command does not startup your application and thus does not know how to resolve the classes in your constructor:
public ConfigurationContext( //How do i resolve this, i dont know?
DbContextOptions<ConfigurationDbContext> options,
ConfigurationStoreOptions storeOptions)
: base(options, storeOptions)
{ }
You need to add a parameterless constructor, as the error suggests:
public ConfigurationContext()
: base(/* todo default static logic here */)
{ /* and here */ }
Why
The database migration tries to create an instance of the ConfigurationContext to determine the 'desired' state (the state you want your database to be after the database migration has been executed).
This migration is a static file inside your project saying which Columns and which indexes etc need to be added or removed to the database to create the 'desired' state.
This Add-Migration command simply reflects your code to find the right context, it does not go through your startup class to see which dependencies you have the find (this would become way to complex since there could also be runtime dependencies or dependencies based on App-settings, etc)

Change MigrationsHistoryTable column names in EF Core

I have a standardized all table and column names in my EF Core database to use snake_case. I was able to change the migrations history table name and schema to match the rest of the database, but I am not able to find a way to change the columns from MigrationId to migration_id and ProductVersion to product_version.
Any ideas on how this could be done?
Here is an example of how to do it on SQL Server.
First, create a custom implementation of SqlServerHistoryRepository overriding ConfigureTable.
class MyHistoryRepository : SqlServerHistoryRepository
{
public MyHistoryRepository(
IDatabaseCreator databaseCreator, IRawSqlCommandBuilder rawSqlCommandBuilder,
ISqlServerConnection connection, IDbContextOptions options,
IMigrationsModelDiffer modelDiffer,
IMigrationsSqlGenerator migrationsSqlGenerator,
IRelationalAnnotationProvider annotations,
ISqlGenerationHelper sqlGenerationHelper)
: base(databaseCreator, rawSqlCommandBuilder, connection, options,
modelDiffer, migrationsSqlGenerator, annotations, sqlGenerationHelper)
{
}
protected override void ConfigureTable(EntityTypeBuilder<HistoryRow> history)
{
base.ConfigureTable(history);
history.Property(h => h.MigrationId).HasColumnName("migration_id");
history.Property(h => h.ProductVersion).HasColumnName("product_version");
}
}
Then replace the replace the service with your custom implementation.
protected override void OnConfiguring(DbContextOptionsBuilder options)
=> options
.UseSqlServer(connectionString)
.ReplaceService<SqlServerHistoryRepository, MyHistoryRepository>();