Skip to content

Commit

Permalink
Moved value object configuration for EFCore to the entity builder lev…
Browse files Browse the repository at this point in the history
…el. (#31)
  • Loading branch information
mgernand authored Dec 13, 2022
1 parent 1150379 commit b70bf38
Show file tree
Hide file tree
Showing 3 changed files with 52 additions and 55 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
namespace Fluxera.ValueObject.EntityFrameworkCore
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Fluxera.Guards;
using JetBrains.Annotations;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;

/// <summary>
/// Extension methods for the <see cref="ModelBuilder" /> type.
/// </summary>
[PublicAPI]
public static class EntityTypeBuilderExtensions
{
/// <summary>
/// Configure the <see cref="EntityTypeBuilder" /> to use the
/// <see cref="PrimitiveValueObjectConverter{TValueObject,TValue}" />.
/// </summary>
/// <param name="entityTypeBuilder"></param>
public static void UsePrimitiveValueObject(this EntityTypeBuilder entityTypeBuilder)
{
Guard.Against.Null(entityTypeBuilder);

IEnumerable<PropertyInfo> properties = entityTypeBuilder.Metadata
.ClrType
.GetProperties()
.Where(type => type.PropertyType.IsPrimitiveValueObject());

foreach(PropertyInfo property in properties)
{
Type enumerationType = property.PropertyType;
Type valueType = enumerationType.GetPrimitiveValueObjectValueType();

Type converterTypeTemplate = typeof(PrimitiveValueObjectConverter<,>);

Type converterType = converterTypeTemplate.MakeGenericType(enumerationType, valueType);

ValueConverter converter = (ValueConverter)Activator.CreateInstance(converterType);

entityTypeBuilder
.Property(property.Name)
.HasConversion(converter);
}
}
}
}

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -54,13 +54,13 @@ protected override void OnModelCreating(ModelBuilder modelBuilder)
foreach(Type type in types)
{
EntityTypeBuilder entityBuilder = modelBuilder.Entity(type);
entityBuilder.UsePrimitiveValueObject();

object[] data = this.SeedData.Where(x => x.GetType() == type).ToArray();
entityBuilder.HasData(data);
}
}

modelBuilder.UsePrimitiveValueObject();

base.OnModelCreating(modelBuilder);
}
}
Expand Down

0 comments on commit b70bf38

Please sign in to comment.