简体   繁体   中英

Extension methods for EntityTypeConfiguration and <datatype>PropertyConfiguration

With Entity Framework I might have a configuration that looks like:

internal class MyDbContext : DbContext
{

  ....

  protected override void OnModelCreating(DbModelBuilder mb)
  {
    builder.Entity<MyEntity>()
      .ToTable("MyTable", "MySchema");

    builder.Entity<MyEntity>()
      .Property(e => e.Name)
      .IsRequired()
      .HaxMaxLength(10);

    builder.Entity<MyEntity>()
      .Property(e => e.City)
      .HaxMaxLength(10);

  }
}

I'd like to write an extension method so I could write it like:

    builder.Entity<MyEntity>()
      .ToTable("MyTable", "MySchema")
      .Property(e => e.Name, 
        n => n.IsRequired()
              .HaxMaxLength(10))
      .Property(e => e.City,
        c => c.HasxMaxLength(50));

I'm pretty sure I have the signature correct, but I don't know how to get the inner plumbing to work correctly.

    public static EntityTypeConfiguration<TEntityType> Property<TEntityType>(
        this EntityTypeConfiguration<TEntityType> instance,
        Expression<Func<TEntityType, byte[]>> propertyExpression, 
        Func<BinaryPropertyConfiguration, BinaryPropertyConfiguration> propertyConfiguration)
        where TEntityType : class
    {
        Func<TEntityType, byte[]> func = propertyExpression.Compile();

        // ??

        return instance;
    }

After a little playing around, I realized I don't need to execute/compile any of it, I just need to chain the parameters together in the correct sequence.

    public static EntityTypeConfiguration<TEntityType> Property<TEntityType>(
        this EntityTypeConfiguration<TEntityType> instance,
        Expression<Func<TEntityType, byte[]>> propertyExpression,
        Func<BinaryPropertyConfiguration, BinaryPropertyConfiguration> propertyConfiguration)
        where TEntityType : class
    {
        propertyConfiguration(instance.Property(propertyExpression));

        return instance;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM