4

I'm using Entity Framework Code First with map classes inheriting from EntityTypeConfiguration. I do this to encapsulate my use of the Code First fluent API for configuring entities.

I would like to be able to examine the configuration settings made in these classes, so that I can apply some of them in my integration testing. I'm using AutoFixture to create entities quickly, and ultimately I want to figure out a way to make some customizations that consume the configurations inside of my EntityTypeConfiguration classes.

But first, I need to figure out how to pull them out...

Here's a use case example:

public class Widget { public string Name { get; set; } }
public class WidgetMap : EntityTypeConfiguration<Widget> {
   this.Property(w => w.Name).HasMaxLength(10);
}

How do I do something like this pseudo-code:

public Widget GetWidgetHonoringStringLengthConstraints(WidgetMap map) {
   var w = new Widget();
   int maxLength = map.GetProperty(p => p.Name).GetMaxLength(); //MAGIC
   string name = new Guid().SubString(0, maxLength);
   w.Name = name;
   return w;
}
Jeff
  • 2,191
  • 4
  • 30
  • 49

1 Answers1

1

I received a reply from Arthur Vickers in the Entity Framework Codeplex Discussions.

Essentially, he told me I'm barking up the wrong tree, because, by design, they didn't want the configuration classes to be inspected from the normal public surface - the idea being that it would pollute the API and trying to find something like the max length of a string would often tell you the story, but not the whole story (the ultimate max length restriction may have come from several conventions, including a default setting), which might not always give you the answer you are really after.

He recommended getting the metadata from the model after being built, through the MetadataWorkspace which can be accessed like this:

((IObjectContextAdapter)myDbContext).ObjectContext.MetadataWorkspace

I haven't pursued implementing this yet, but I'll mark this as the answer until someone submits another answer (either an example of this before I get around to it, or another option).

Jeff
  • 2,191
  • 4
  • 30
  • 49