Skip to content
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

Enable working with lazy loading proxies SN-776 #121

Merged
merged 7 commits into from
Feb 17, 2025
Merged
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
@@ -1,6 +1,9 @@
using Microsoft.AspNetCore.Components;
using Saritasa.NetForge.Domain.UseCases.Interfaces;
using Saritasa.NetForge.Domain.UseCases.Metadata.GetEntityById;
using Saritasa.NetForge.Infrastructure.EfCore.Extensions;
using Saritasa.NetForge.Infrastructure.EfCore.Services;
using Saritasa.NetForge.Infrastructure.Helpers;

namespace Saritasa.NetForge.Controls.CustomFields;

Expand All @@ -24,7 +27,6 @@ public IEnumerable<T> PropertyValue

private IEnumerable<T> NavigationInstances { get; set; } = null!;


private GetEntityDto EntityMetadata { get; set; } = null!;

/// <inheritdoc />
Expand All @@ -37,7 +39,14 @@ protected override async Task OnInitializedAsync()
NavigationInstances = Service
.GetQuery(entityType)
.Cast<T>()
.OrderBy(instance => instance);
.OrderBy(instance => instance).ToList();

// In case of lazy loading - convert proxies to POCO instances.
if (NavigationInstances.Any() && NavigationInstances.First()!.GetType().IsLazyLoadingProxy())
{
NavigationInstances = NavigationInstances
.Select(instance => ProxyToPocoConverter.ConvertProxyToPoco(instance)).Cast<T>();
}

EntityMetadata = await EntityService.GetEntityByTypeAsync(entityType, CancellationToken.None);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,13 @@ public static class CloneExtensions

var serializeSettings = new JsonSerializerSettings
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
ReferenceLoopHandling = ReferenceLoopHandling.Ignore,

// Ignore errors during serialization (in case of shadow properties in LazyLoadingProxies).
Error = (serializer, err) =>
{
err.ErrorContext.Handled = true;
}
};

serializeSettings.Converters.Add(new DecimalJsonConverter());
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
namespace Saritasa.NetForge.Infrastructure.EfCore.Extensions;

/// <summary>
/// Contains extension methods for entity proxies.
/// </summary>
public static class EntityProxyExtensions
{
private const string CastleProxiesNamespace = "Castle.Proxies";

/// <summary>
/// Checks if the given type is a lazy loading proxy.
/// </summary>
/// <param name="type">The type to check.</param>
/// <returns>True if the type is a lazy loading proxy, otherwise false.</returns>
public static bool IsLazyLoadingProxy(this Type type)
{
var baseType = type.BaseType;

// Check if the type is a proxy type generated by EF Core for lazy loading.
return baseType != null && type.Namespace == CastleProxiesNamespace;
}

/// <summary>
/// Gets the POCO type of the entity.
/// </summary>
/// <param name="entity">Entity instance.</param>
/// <returns>The POCO type if the entity is a lazy loading proxy.</returns>
/// <exception cref="InvalidOperationException">Throws if the provided entity is not a lazy loading proxy.</exception>
public static Type GetPocoType(this object entity)
{
var entityType = entity.GetType();

if (!entityType.IsLazyLoadingProxy())
{
throw new InvalidOperationException($"The provided entity of type {entityType.Name} is not a lazy loading proxy.");
}

return entityType.BaseType!;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,13 @@ private DbContext GetDbContextThatContainsEntity(Type clrType)
continue;
}

// Check if the entity type is a proxy type generated by EF Core for lazy loading.
// If it is, get the actual type to be able to work with it.
if (clrType.IsLazyLoadingProxy())
{
clrType = clrType.BaseType!;
}

var dbContext = (DbContext)dbContextService;
var entityType = dbContext.Model.FindEntityType(clrType);

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
using System.Collections;
using Saritasa.NetForge.Infrastructure.EfCore.Extensions;

namespace Saritasa.NetForge.Infrastructure.EfCore.Services;

/// <summary>
/// Convert entities with lazy loading proxies to POCO entities.
/// </summary>
public static class ProxyToPocoConverter
{
/// <summary>
/// Converts a proxy entity to a POCO entity.
/// </summary>
/// <param name="source">The source proxy entity.</param>
/// <param name="navigationPropertyNames">The list of navigation property names.</param>
/// <returns>The POCO entity.</returns>
public static object? ConvertProxyToPoco(object? source, IList<string>? navigationPropertyNames = null)
{
switch (source)
{
case null:
return default;

// Sometimes the source is a collection of proxy entities.
case IEnumerable<object> sourceCollection:
{
var sourceType = source.GetType();

// Get the item type of the collection to avoid boxing issues.
var itemType = sourceType.GetGenericArguments().FirstOrDefault() ?? typeof(object);
var pocoCollectionType = typeof(List<>).MakeGenericType(itemType);
var pocoCollection = (IList)Activator.CreateInstance(pocoCollectionType)!;

foreach (var item in sourceCollection)
{
pocoCollection.Add(ConvertProxyToPoco(item));
}
return pocoCollection;
}
}

var entityType = source.GetPocoType();

// Create new instance of the POCO entity.
var pocoInstance = Activator.CreateInstance(entityType)!;

// Copy the properties from the proxy to the POCO.
foreach (var property in entityType.GetProperties())
{
// Exclude the navigation properties because they are the proxies as well.
if (navigationPropertyNames != null && navigationPropertyNames.Contains(property.Name))
{
continue;
}

// Exclude indexers, read-only and write-only properties.
if (!property.CanWrite || !property.CanRead || property.GetIndexParameters().Length > 0)
{
continue;
}

try
{
var value = property.GetValue(source);

// Skip the property if it is a proxy.
if (value != null && value.GetType().IsLazyLoadingProxy())
{
continue;
}

// Check if the property is a collection of proxy entities.
if (value is IEnumerable<object> collection)
{
var firstItem = collection.FirstOrDefault();
if (firstItem != null && firstItem.GetType().IsLazyLoadingProxy())
{
continue;
}
}

property.SetValue(pocoInstance, value);
}
catch
{
// Skip the property if it cannot be copied.
}
}

if (navigationPropertyNames == null)
{
return pocoInstance;
}

// Do the same for the navigation properties recursively because they can be proxies as well.
foreach (var navigationName in navigationPropertyNames)
{
var property = source.GetType().GetProperty(navigationName);
var propertyValue = property?.GetValue(source);

if (property == null)
{
continue;
}

var navigationPoco = ConvertProxyToPoco(propertyValue);
entityType.GetProperty(navigationName)?.SetValue(pocoInstance, navigationPoco);
}

return pocoInstance;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@
using Saritasa.NetForge.Domain.UseCases.Interfaces;
using Saritasa.NetForge.Domain.UseCases.Metadata.GetEntityById;
using Saritasa.NetForge.Infrastructure.Abstractions.Interfaces;
using Saritasa.NetForge.Infrastructure.EfCore.Extensions;
using Saritasa.NetForge.Infrastructure.EfCore.Services;

namespace Saritasa.NetForge.MVVM.ViewModels.EditEntity;

Expand Down Expand Up @@ -83,11 +85,23 @@ public override async Task LoadAsync(CancellationToken cancellationToken)

var includedNavigationNames = Model.Properties
.Where(property => property is NavigationMetadataDto)
.Select(property => property.Name);
.Select(property => property.Name).ToList();

Model.EntityInstance = await dataService
.GetInstanceAsync(instancePrimaryKey, Model.ClrType!, includedNavigationNames, CancellationToken);

var instanceType = Model.EntityInstance.GetType();

// Check if the entity type is a proxy type generated by EF Core for lazy loading and use the POCO type
// instead.
// Proxy types raise serialization issues when we try to serialize it to JSON.
if (instanceType.IsLazyLoadingProxy())
{
var pocoInstance = ProxyToPocoConverter.ConvertProxyToPoco(Model.EntityInstance, includedNavigationNames);
Model.EntityInstance = pocoInstance;
}

// We have to keep the original entity to work with navigation properties.
Model.OriginalEntityInstance = Model.EntityInstance.CloneJson();

FieldErrorModels = Model.Properties
Expand Down
Loading