Get the EntitySet name from an EntityType in EF

前端 未结 3 1359
时光取名叫无心
时光取名叫无心 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:32

    This extension may be useful

    public static class MyExtensions
    {
        public static string GetEntitySetName(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(), myEntityInstance);
    

提交回复
热议问题