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

EF Core/Dapper converters and clean architecture #111

Open
modabas opened this issue Sep 11, 2023 · 6 comments · May be fixed by #126
Open

EF Core/Dapper converters and clean architecture #111

modabas opened this issue Sep 11, 2023 · 6 comments · May be fixed by #126

Comments

@modabas
Copy link

modabas commented Sep 11, 2023

First of all, thanks for this awesome library, great work. Reduces boiler plate code required for strongly typed ids to near zero.

Unfortunately, i have come across a problem integrating it to an existing project designed with clean architecture. Using eShopOnWeb project as reference, general solution structure when using EF Core (or any ORM) would be:
Application Core project => db entities as poco, without any EF Core specific decoration
Infrastructure project => db context and db entity type configurations with fluent api.

However, as strongly typed id partial structs are defined along with db entities in Application Core project, StronglyTypedId attribute generates converters in that project which makes Application Core project dependent on Entity Framework Core (or Dapper if dapper converter is generated)

Is there a way to generate converters seperately, similar to fluent api decouples entity declaration and configuration.

Regards,

@ardalis
Copy link
Contributor

ardalis commented Nov 10, 2023

I just ran into this same thing playing with this. Is there a way to have the converts generate in a separate project from the definition of the id type?

@andrewlock
Copy link
Owner

There isn't currently a way to make this work, it requires a bit of work. That said, I'm working on a fundamental redesign of the library in #117, and I think that flexibility will make it easy to add a way to do this

@DorianGreen
Copy link

Could we create an attribute that accepts an existing StronglyTypedId type on a new partial class and uses a generator to run templates based on the provided ID type?

This way we can split EF converter or any other template to other assemblies.
We might need to expose the attribute in the build output for this to work.

An extension could accept an assembly and/or namespace and generate the template for each matching StronglyTypedId

@fredrikahs
Copy link

Great library, and this feature would be nice!

In the meantime I wanted to share a bit of a workaround I made with a custom template, an interface and a generic converter. It uses a static abstract method in the interface, so requires .NET 8+. Seems to work fine so far, but I haven't tested it extensively. Use at your own risk 🙂

public interface ICreatableStronglyTypedId<out TId, TValue>
    where TId : ICreatableStronglyTypedId<TId, TValue>
{
    static abstract TId Create(TValue value);
    TValue Value { get; }
}

Templates named guid-create.typedid, string-create.typedid etc

    partial struct PLACEHOLDERID : global::My.Namespace.ICreatableStronglyTypedId<PLACEHOLDERID, global::System.Guid>
    {
        public static PLACEHOLDERID Create(global::System.Guid value) => new(value);
    }

Add to csproj

  <ItemGroup>
    <AdditionalFiles Include="guid-create.typedid" />
    <AdditionalFiles Include="string-create.typedid" />
  </ItemGroup>

And the converter

internal sealed class StronglyTypedIdValueConverter<TId, TValue> : ValueConverter<TId, TValue>
    where TId : ICreatableStronglyTypedId<TId, TValue>
{
    public StronglyTypedIdValueConverter() : this(null) { }

    public StronglyTypedIdValueConverter(ConverterMappingHints? mappingHints = null)
        : base(
            id => id.Value,
            value => Create(value),
            mappingHints
        )
    {
    }

    private static TId Create(TValue value) => TId.Create(value);
}

I also added some extension methods to simplify the entity configuration a bit

internal static class StronglyTypedIdValueConverterExtensions
{
    public static PropertyBuilder<TId> HasStronglyTypedId<TEntity, TId>(
        this EntityTypeBuilder<TEntity> builder,
        Expression<Func<TEntity, TId>> propertyExpression)
        where TEntity : class
        where TId : ICreatableStronglyTypedId<TId, Guid>
    {
        return builder.Property(propertyExpression)
            .HasConversion<StronglyTypedIdValueConverter<TId, Guid>>();
    }

    public static PropertyBuilder<TId> HasStronglyTypedStringId<TEntity, TId>(
        this EntityTypeBuilder<TEntity> builder,
        Expression<Func<TEntity, TId>> propertyExpression)
        where TEntity : class
        where TId : ICreatableStronglyTypedId<TId, string>
    {
        return builder.Property(propertyExpression)
            .HasConversion<StronglyTypedIdValueConverter<TId, string>>();
    }
}

Use with

[assembly: StronglyTypedIdDefaults(Template.Guid, StronglyTypedIdTemplates.Guids.Create)]

[StronglyTypedId]
public readonly partial struct MyId;

[StronglyTypedId(Template.String, "string-create")]
public readonly partial struct MyOtherId;

internal sealed class MyEntityTypeConfiguration : IEntityTypeConfiguration<MyEntity>
{
    public void Configure(EntityTypeBuilder<MyEntity> builder)
    {
        builder.HasStronglyTypedId(x => x.Id);
        builder.HasStronglyTypedStringId(x => x.ExternalId);

        // or if you don't want the extension method 
        builder
            .Property(x => x.Id)
            .HasConversion<StronglyTypedIdValueConverter<MyId, Guid>>()
    } 
}

@ardalis
Copy link
Contributor

ardalis commented Jan 8, 2025

FYI I've been playing with Vogen for this in the sample app in my CleanArchitecture repo and it works great.

@fredrikahs
Copy link

fredrikahs commented Jan 8, 2025

Looks interesting, I'll try it out!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

5 participants