none
DbContext modelBuilder write only? RRS feed

  • Question

  • Is there any way to read the configuration from a DbContext instance?

    I need to be able to read the max length of property entity_id on SomeEntity that was set during OnModelCreating.

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Configurations.Add(new SomeEntityMap());

    }

    public class SomeEntityMap : EntityTypeConfiguration<SomeEntity>
    {
            public FI_SomeEntityMap()
            {
                // Primary Key
                this.HasKey(t => t.entity_id);

                // Properties
                this.Property(t => t.entity_id)
                    .IsRequired()
                    .IsFixedLength()
                    .HasMaxLength(16);

     }


    Thursday, October 31, 2013 11:27 PM

Answers

  • Hello,

    As far as I know, there is no ready way for us to do this with DbContext. For achieving this, we need to translate it to ObjectContext object and use its metadata.

    The method is like below:

    using (UserRoleContext db = new UserRoleContext())
    
                {
    
                    ObjectContext objectContext = ((IObjectContextAdapter)db).ObjectContext;
    
    
                    Code_First.S2013_10.User user = new S2013_10.User();
    
    
                    string queryPropertyName = "Name";
    
    
                    var queryResult = from meta in objectContext.MetadataWorkspace.GetItems(DataSpace.CSpace)
    
                                       .Where(m => m.BuiltInTypeKind == BuiltInTypeKind.EntityType)
    
                                      from p in (meta as EntityType).Properties
    
                                         .Where(p => p.DeclaringType.Name == user.GetType().Name
    
                                             && p.Name == queryPropertyName
    
                                             && p.TypeUsage.EdmType.Name == queryPropertyName.GetType().Name)
    
                                      select p.TypeUsage.Facets["MaxLength"].Value;
    
                    if (queryResult.Count() > 0)
    
                    {
    
                        Console.WriteLine("The " + queryPropertyName + " Length is:" + queryResult.First());
    
                    }
    
                }
    

    The result:

    If this does not work for you, please let me know.

    Regards.


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    • Marked as answer by deo.is Friday, November 1, 2013 3:25 PM
    Friday, November 1, 2013 2:23 AM
    Moderator