Run Scaffolding Command in C# Code with Powershell Runspace

demetsen

Member
Joined
Jan 24, 2022
Messages
14
Programming Experience
1-3
Hi,

I need to do scaffolding in code. To do this I wrote this method;

RunScript Method:
public string RunScript(string scriptText)
        {
            string dir = @"C:\Users\demetsen\source\repos\ScaffoldingInCode\ScaffoldingInCode";
            Directory.SetCurrentDirectory(dir);
            Runspace runspace = RunspaceFactory.CreateRunspace();
            runspace.Open();
            Pipeline pipeline = runspace.CreatePipeline();
            pipeline.Commands.AddScript(scriptText);
            Collection<PSObject> results = pipeline.Invoke();
            runspace.Close();
            StringBuilder stringBuilder = new StringBuilder();
            foreach (PSObject obj in results)
            {
                stringBuilder.AppendLine(obj.ToString());
            }
            return stringBuilder.ToString();
        }

The string value that I send to the method is;
scriptText:
string scriptText = "dotnet ef dbcontext scaffold \"Data Source = (DESCRIPTION = (ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521))(CONNECT_DATA = (SERVER = DEDICATED)(SERVICE_NAME = XE))); User Id = ***;Password=***;\" Oracle.EntityFrameworkCore --context-dir Data --output-dir Models --context ModelContext -f;";

It returns this message;
result:
Build started...
Build failed. Use dotnet build to see the errors.

But when I apply "dotnet build" command in powershell there is no errors at all. This command works when I use it in the powershell screen manually.
Is the something that I miss in the Runscript Method?


Note: I used oracle database in this sample but MsSql also gives the same result.

Thank you.
 
This command works when I use it in the powershell screen manually.
It likely works because when you launch PowerShell, it loads your profile. The profile will include various path settings and default modules. From what I recall about PowerShell hosting, if you host the engine yourself, it won't load the current user profile.
 
It likely works because when you launch PowerShell, it loads your profile. The profile will include various path settings and default modules. From what I recall about PowerShell hosting, if you host the engine yourself, it won't load the current user profile.
Actually, I am not sure if this is a good practise to do scaffolding with powershell in code.
The need is doing scaffolding after installing the program and running it. Using Powershell is just a possible option for me to do.
 
Back
Top Bottom