Get the EntitySet name from an EntityType in EF

前端 未结 3 1347
时光取名叫无心
时光取名叫无心 2020-12-15 06:51

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\"?

相关标签:
3条回答
  • 2020-12-15 07:21

    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 讨论(0)
  • 2020-12-15 07:32

    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);
    
    0 讨论(0)
  • 2020-12-15 07:34

    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();
    
    0 讨论(0)
提交回复
热议问题