Get entity facets and other metadata on runtime

后端 未结 1 727
孤街浪徒
孤街浪徒 2021-01-24 11:25

I have .NET 4.0 WinForms Application, and I use Entity Framework 5 with Model First Approach. In VS EF Designer, I have created a dozen or so entities with a lot of scalar prope

1条回答
  •  温柔的废话
    2021-01-24 11:51

    This should help you get started, but you'd need to get to debugger and test specifically to get what you need...

    A sample code...

    using (var db = new MyContext())
    {
    var objectContext = ((IObjectContextAdapter)db).ObjectContext;
    
    var baseset = objectContext
        .MetadataWorkspace
        .GetEntityContainer(objectContext.DefaultContainerName, DataSpace.CSpace)
        .BaseEntitySets
        .First(meta => meta.ElementType.Name == "YourEntityClassName");
    
    var elementType = objectContext
        .MetadataWorkspace
        .GetEntityContainer(objectContext.DefaultContainerName, DataSpace.CSpace)
        .BaseEntitySets
        .First(meta => meta.ElementType.Name == "YourEntityClassName")
        .ElementType;
    
    EdmMember member = elementType.Members[2];
    
    Facet item;
    // if (member.TypeUsage.Facets.TryGetValue(EdmProviderManifest.StoreGeneratedPatternFacetName, false, out item))
    if (member.TypeUsage.Facets.TryGetValue("StoreGeneratedPattern", false, out item))
    {
        var value = ((StoreGeneratedPattern)item.Value) == StoreGeneratedPattern.Computed;
    }
    

    But that's just part of the story.

    What I realized is that's working in some cases (thus you need to experiment a bit) depending on what you need. But you also have other spaces in there - e.g. the SSpace. So e.g. for table names this works better...

    var ssSpaceSet = objectContext.MetadataWorkspace.GetItems(DataSpace.SSpace).First()
        .BaseEntitySets
        .First(meta => meta.ElementType.Name == "YourTableName");
    

    ...and then private Table property.

    In your case you should most info in there - but e.g. the above store generated is not populated there - but in some other 'space' I guess (more in one of the links on that).

    And take a look at the following links:


    Get Model schema to programmatically create database using a provider that doesn't support CreateDatabase
    How I can read EF DbContext metadata programmatically?
    How check by unit test that properties mark as computed in ORM model?

    0 讨论(0)
提交回复
热议问题