Get Identity Field out of KeyMembers

冷暖自知 提交于 2019-12-20 03:21:57

问题


I would like to get the KeyMembers where I have set in the Edmx the StoreGeneratedPattern to Identity is there a way to do this?

I can get the KeyMembers with this code:

private static IEnumerable<EdmMember> GetKeyMembers(string entityName)
{
    var objectContext = EntityModel.ObjectContext;

    var metaData = objectContext
        .MetadataWorkspace
        .GetEntityContainer(objectContext.DefaultContainerName, DataSpace.CSpace)
        .BaseEntitySets
        .FirstOrDefault(x => x.ElementType.Name == entityName);

    return metaData.ElementType.KeyMembers;
}

The problem I have with this that it also returns foreign keys, but I just want to get PrimaryKeys with auto incrementing values.


回答1:


From a given MetadataWorkspace, let's call mw, i use this:

var cSpaceEntities = mw.GetItems(DataSpace.CSpace).OfType<EntityType>();

foreach (var entity in cSpaceEntities) {
     var autoIds = entity.KeyMembers.Where(p => 
                        p.MetadataProperties
                            .Any(m =>    m.PropertyKind == PropertyKind.Extended 
                                  && Convert.ToString(m.Value) == "Identity")).ToArray();
            }

please test




回答2:


The store-generated pattern is in the SSDL content of the EF model. Here's an example of how you can get the properties with identity specification:

var items = oc.MetadataWorkspace.GetItems(DataSpace.SSpace).OfType<EntityType>();
foreach (var entityType in items)
{
    var props = string.Join(",", entityType.Properties
                .Where(x => x.IsStoreGeneratedIdentity));
    Trace.WriteLine(string.Format("{0}: {1}", entityType.Name, props));
}

(where oc is an ObjectContext)



来源:https://stackoverflow.com/questions/21709302/get-identity-field-out-of-keymembers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!