开发者

Get the EntitySet name from an EntityType in EF

开发者 https://www.devze.com 2022-12-27 22:19 出处:网络
Given an EntityType, such as \"Contact\", how can I derive from it the name of the EntitySet开发者_开发知识库 it would belong to, i.e. the pluralization such as \"Contacts\"?If you already have an att

Given an EntityType, such as "Contact", how can I derive from it the name of the EntitySet开发者_开发知识库 it would belong to, i.e. the pluralization such as "Contacts"?


If you already have an attached entity (obviously you don't need the first line, just use your existing entity):

  Contact c = context.Contacts.Where(x => x.blah).FirstOrDefault();
  string setName = c.EntityKey.EntitySetName;

Or if you don't:

 string className = typeof(Contact).Name
 var container =   
    context.MetadataWorkspace.GetEntityContainer(context.DefaultContainerName, DataSpace.CSpace);
    string setName = (from meta in container.BaseEntitySets
                                          where meta.ElementType.Name == className
                                          select meta.Name).First();


This extension may be useful

public static class MyExtensions
{
    public static string GetEntitySetName<T>(this ObjectContext context)
    {
        string className = typeof(T).Name;

        var container = context.MetadataWorkspace.GetEntityContainer(context.DefaultContainerName, DataSpace.CSpace);
        string entitySetName = (from meta in container.BaseEntitySets
                                where meta.ElementType.Name == className
                                select meta.Name).First();

        return entitySetName;
    }
}

And use it like:

db.AttachTo(db.GetEntitySetName<MyEntityType>(), myEntityInstance);


Here is a method that works similar to the accepted answer except that this supports a) proxy types (for example, if you dynamically get the type of an EF6 entity it could be of type "Contact_1A2B3C4D5E" instead of "Contact") and b) inheritance (table-per-type, table-per-hierarchy).

private static string GetEntitySetName(ObjectContext objectContext, Type type)
{
    if (objectContext == null) throw new ArgumentNullException(nameof(objectContext));
    if (type == null) throw new ArgumentNullException(nameof(type));

    EntityContainer container = objectContext.MetadataWorkspace.GetEntityContainer(objectContext.DefaultContainerName, DataSpace.CSpace);

    return container.BaseEntitySets
        .Where(x =>
            (x.ElementType.Name == type.Name) ||
            (x.ElementType.Name == type.BaseType?.Name) ||
            (x.ElementType.Name == type.BaseType?.BaseType?.Name)
        )
        .Select(x => x.Name)
        .FirstOrDefault() ?? throw new ArgumentException($"Specified type is not an entity type.", nameof(type));
}
0

精彩评论

暂无评论...
验证码 换一张
取 消