How to get the MaxLength from a Fluent API mapping specification in runtime?

1.6k views Asked by At

I need to retrieve the maxlength value specified for a field using Fluent API and Entity Framework 5 Code First.

I have seen a couple of examples using MetadataWorkspace but it doesn't work when you use Fluent API. For instance, I tried this code but the value for MaxLenght is always null:

ObjectContext.MetadataWorkspace.GetItem<GlobalItem>(typeof(TEntity).FullName, DataSpace.OSpace).MetadataProperties[field].TypeUsage.Facets["MaxLength"].Value

Inside the Fluent API configuration file I have the following code for the necessary properties:

Property(t => t.Name).HasMaxLength(50);

I know the mapping is working because if I try to save the object with more than 50 characters in that field it fails.

I just need guidance for getting the maxlenght value but to give some perspective the goal is:

  1. Create new Foo object
  2. Get the maxlength value defined for Bar property using Fluent API.
  3. Apply certain rules based on the maxlength to the string to be assigned to Bar.
  4. Save.

Thanks in advance.

1

There are 1 answers

2
phil soady On BEST ANSWER

You should use the storage model. Check docu on the Enum DataSpace Use The EntityType items.

  [TestMethod]
    public void EFToolsTest() {

        var context = new BosMasterDbContext("MYDBCONTEXT");
        ObjectContext objContext = ((IObjectContextAdapter)context).ObjectContext;
        MetadataWorkspace workspace = objContext.MetadataWorkspace;

        var xyz = workspace.GetItems<EntityType>(DataSpace.SSpace);
        foreach (var ET in xyz) {
            foreach (var sp in ET.Properties) {
                Debug.WriteLine(sp.Name + ":" + sp.MaxLength);

                }
            }
        }