Skip to content

Adds support for parameter binding #48

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 7 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<Version>2.5.0-rc1</Version>
<Version>2.5.0-rc2</Version>
<Description>A functional extensions for Entity Framework.</Description>
<PackageProjectUrl>https://github.com/codehardth/Codehard.Common/tree/main/src/Codehard.Functional</PackageProjectUrl>
<RepositoryUrl>https://github.com/codehardth/Codehard.Common/tree/main/src/Codehard.Functional</RepositoryUrl>
Expand All @@ -13,9 +13,9 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="LanguageExt.Core" Version="4.4.2"/>
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="7.0.2"/>
<PackageReference Include="Microsoft.EntityFrameworkCore.Relational" Version="7.0.2"/>
<PackageReference Include="LanguageExt.Core" Version="4.4.2" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="7.0.2" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Relational" Version="7.0.2" />
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,6 @@

internal static class ConfigurationCache
{
// (Entity Type, Property Name) -> Backing Field Name
public static readonly Dictionary<(Type, string), string> BackingField = new();
// (Entity Type FullName, Property Name) -> Backing Field Name
public static readonly Dictionary<(string, string), string> BackingField = new();
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,7 @@ namespace Microsoft.EntityFrameworkCore;
public static class CodehardDbContextOptionsBuilderExtensions
{
public static DbContextOptionsBuilder AddOptionalTranslator(this DbContextOptionsBuilder optionsBuilder)
=> optionsBuilder.AddInterceptors(new OptionalTranslatorExpressionInterceptor());
=> optionsBuilder
.AddInterceptors(new OptionalTranslatorExpressionInterceptor())
.AddInterceptors(new OptionalQueryInterceptor());
}
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,73 @@ public static PropertyBuilder HasOptionProperty<TEntity, TProperty>(
Expression<Func<TEntity, TProperty>> propertyExpression,
string? backingField = default)
where TEntity : class
{
var (backingFieldInfo, backingFieldName, propertyName) = GetBackingField(propertyExpression, backingField);

builder.Ignore(propertyName);

return
builder.Property(backingFieldInfo.FieldType, backingFieldName)
.HasColumnName(propertyName)
.IsRequired(false);
}

/// <summary>
/// Configure a property of <see cref="Option{TEntity}"/> using a backing field.
/// </summary>
/// <param name="builder"></param>
/// <param name="propertyExpression"></param>
/// <param name="backingField"></param>
/// <typeparam name="TOwner"></typeparam>
/// <typeparam name="TProperty"></typeparam>
/// <typeparam name="TDependent"></typeparam>
/// <returns></returns>
/// <exception cref="Exception"></exception>
public static PropertyBuilder HasOptionProperty<TOwner, TDependent, TProperty>(
this OwnedNavigationBuilder<TOwner, TDependent> builder,
Expression<Func<TDependent, TProperty>> propertyExpression,
string? backingField = default)
where TOwner : class
where TDependent : class
{
var (backingFieldInfo, backingFieldName, propertyName) = GetBackingField(propertyExpression, backingField);

builder.Ignore(propertyName);

var ownerName = builder.Metadata.PrincipalToDependent?.Name;

return
builder.Property(backingFieldInfo.FieldType, backingFieldName)
.HasColumnName($"{ownerName}_{propertyName}")
.IsRequired(false);
}

private static ReferenceNavigationBuilder HasOneOption<TEntity, TRelatedEntity>(
this EntityTypeBuilder<TEntity> builder,
Expression<Func<TEntity, TRelatedEntity?>> navigationExpression)
where TEntity : class
where TRelatedEntity : IOptional
{
var (backingFieldInfo, backingFieldName, propertyName) = GetBackingField(navigationExpression, default);

return builder.HasOne(backingFieldInfo.FieldType, backingFieldName);
}

private static ReferenceReferenceBuilder WithOneOption<TEntity, TRelation>(
this ReferenceNavigationBuilder builder,
Expression<Func<TEntity, TRelation>> navigationExpression)
where TEntity : class
{
var (backingFieldInfo, backingFieldName, propertyName) = GetBackingField(navigationExpression);

return builder.WithOne(backingFieldName);
}

private static (FieldInfo BackingField, string BackingFieldName, string PropertyName) GetBackingField
<TEntity, TProperty>(
Expression<Func<TEntity, TProperty>> propertyExpression,
string? backingField = default)
where TEntity : class
{
var property =
((MemberExpression)propertyExpression.Body).Member;
Expand All @@ -40,33 +107,31 @@ public static PropertyBuilder HasOptionProperty<TEntity, TProperty>(
throw new Exception("Property is not an option.");
}

backingField ??= property.GetBackingFieldName();
var actualBackingField = backingField ?? property.GetBackingFieldName();

var backingFieldInfo =
property.DeclaringType?.GetField(backingField, BindingFlags.Instance | BindingFlags.NonPublic);
property.DeclaringType?.GetField(actualBackingField, BindingFlags.Instance | BindingFlags.NonPublic);
var genericType = propertyType.GenericTypeArguments[0];
var expectedType = genericType.IsValueType ? typeof(Nullable<>).MakeGenericType(genericType) : genericType;

if (backingFieldInfo == null)
if (backingFieldInfo == null || backingFieldInfo.FieldType != expectedType)
{
throw new Exception($"Unable to find backing field '{backingField}' in {property.DeclaringType}.");
throw new Exception(
$"Unable to find backing field '{actualBackingField}' with type {expectedType} in {property.DeclaringType}.");
}

var entityType = property.DeclaringType!;
var cacheKey = (entityType, propertyName);
var cacheKey = (entityType.FullName, propertyName);

if (ConfigurationCache.BackingField.ContainsKey(cacheKey))
{
ConfigurationCache.BackingField[cacheKey] = backingField;
ConfigurationCache.BackingField[cacheKey] = actualBackingField;
}
else
{
ConfigurationCache.BackingField.Add(cacheKey, backingField);
ConfigurationCache.BackingField.Add(cacheKey, actualBackingField);
}

builder.Ignore(propertyName);

return
builder.Property(backingFieldInfo.FieldType, backingField)
.HasColumnName(propertyName)
.IsRequired(false);
return (backingFieldInfo, actualBackingField, propertyName);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
using System.Collections;
using System.Data.Common;
using LanguageExt;
using Microsoft.EntityFrameworkCore.Diagnostics;

namespace Codehard.Functional.EntityFramework.Interceptors;

public sealed class OptionalQueryInterceptor : DbCommandInterceptor
{
public override InterceptionResult<DbDataReader> ReaderExecuting(
DbCommand command,
CommandEventData eventData,
InterceptionResult<DbDataReader> result)
{
foreach (DbParameter param in command.Parameters)
{
var type = param.Value?.GetType();

if (type is not { IsGenericType: true })
{
continue;
}

if (type.GetGenericTypeDefinition() == typeof(Option<>))
{
var enumerable = (IEnumerable)param.Value!;
var enumerator = enumerable.GetEnumerator();
var hasValue = enumerator.MoveNext();

param.Value = hasValue ? enumerator.Current : DBNull.Value;
}
}

return base.ReaderExecuting(command, eventData, result);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,14 @@ namespace Codehard.Functional.EntityFramework.Interceptors;

public sealed class OptionalTranslatorExpressionInterceptor : IQueryExpressionInterceptor
{
private static OptionExpressionVisitor Visitor = new();

Expression IQueryExpressionInterceptor.QueryCompilationStarting(
Expression queryExpression,
QueryExpressionEventData eventData) =>
new OptionExpressionVisitor().Visit(queryExpression)!;
QueryExpressionEventData eventData)
{
var translatedExpression = Visitor.Visit(queryExpression)!;

return translatedExpression;
}
}
Loading