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

Use generic attribute for EntityTypeConfiguration attribute #30606

Closed
JohnyL opened this issue Apr 1, 2023 · 1 comment
Closed

Use generic attribute for EntityTypeConfiguration attribute #30606

JohnyL opened this issue Apr 1, 2023 · 1 comment

Comments

@JohnyL
Copy link

JohnyL commented Apr 1, 2023

In EF Core 6.0 new EntityTypeConfiguration attribute was introduced. It's handy very much. Now it's possible to move configuration logic into another file in the same project or even into another assembly. But there's one problem with it.
Say, we have simple entity class and configuration for this entity.

[EntityTypeConfiguration(typeof(ConsumerConfiguration))]
public class Consumer
{
  public required int Id { get; set; }
  public required string Name { get; set; }
}

public class ConsumerConfiguration : IEntityTypeConfiguration<Consumer>
{
  public void Configure(EntityTypeBuilder<Consumer> builder)
  {
      // Implementation omitted
  }
}

The problem with EntityTypeConfiguration is that at compile time there's no check for the type used as argument for it. It means I can write the following, which will compile fine but will generate exception at run time:

[EntityTypeConfiguration(typeof(int))]
public class Consumer { }

Since C#11 it's possible to use generic attributes. For EntityTypeConfiguration it means that we could write the following:

[EntityTypeConfiguration<ConsumerConfiguration>]
public record Consumer { }

The advantage is that we now can have type constraint:

[AttributeUsage(AttributeTargets.Class)]
public sealed class EntityTypeConfigurationAttribute<T>
    : Attribute where T : IEntityTypeConfiguration<T> { }

If class does not implement IEntityTypeConfiguration<>, then code won't compile the code and IDE will show red squiggles.

@roji
Copy link
Member

roji commented Apr 1, 2023

Duplicate of #30072

@roji roji marked this as a duplicate of #30072 Apr 1, 2023
@ajcvickers ajcvickers closed this as not planned Won't fix, can't repro, duplicate, stale Apr 5, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants