Adrian Adrian - 2 months ago 11x
C# Question

Getting the namespace of a ProjectItem

I'm writing a VSIX extension that extends

which does some things after an Entity Data Model is updated or generated.

public class ModelGenerationExtension : IModelGenerationExtension
public void OnAfterModelGenerated(ModelGenerationExtensionContext context)
public void OnAfterModelUpdated(UpdateModelExtensionContext context)
//need namespace of context.ProjectItem here

Since this is operating on an entity data model, the
will be an .edmx file - let's call this
. This will contain a file named
which in turn has some nested .cs files each associated to an entity.

What I need to do is get the namespace of one of these .cs files (all entities will be on the same namespace) from the

enter image description here

How can I go about this ?


It's a while ago since I developed a VS extension, but I looked at some of my old code on how to search for those things. Maybe there are newer technologies today, but this is what I know:

At first you should find the correct file by iterating through the child ProjectItems of the item you got for your Model1.edmx to find the *.cs files:

ProjectItem tt = context.ProjectItem.ProjectItems.OfType<ProjectItem>()
                        .FirstOrDefault(item => item.Name == "");

ProjectItem cs = tt.ProjectItems.OfType<ProjectItem>()
                        .FirstOrDefault(item => item.Name.EndsWith(".cs"));

Then you could use the FileCodeModel of this ProjectItem cs to search for the first namespace configuration:

CodeNamespace nsp = cs.FileCodeModel.CodeElements.Cast<CodeElement>().

And there you should have your namespace element. CodeNamespace has a property Name and a FullName.

I put this together from what I read in my old codes, but could not test it right now. You need to add error handling and I'm not 100% sure that the files hierarchy as you described it is really reproduced like that in the ProjectItems hierarchy.