-
Notifications
You must be signed in to change notification settings - Fork 3.2k
/
Copy pathEntityFramework.psm1
1005 lines (822 loc) · 33 KB
/
EntityFramework.psm1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
$ErrorActionPreference = 'Stop'
$EFDefaultParameterValues = @{
ProjectName = ''
ContextTypeName = ''
}
#
# Use-DbContext
#
Register-TabExpansion Use-DbContext @{
Context = { param ($tabExpansionContext) GetContextTypes $tabExpansionContext.Project $tabExpansionContext.StartupProject $tabExpansionContext.Environment }
Project = { GetProjects }
StartupProject = { GetProjects }
}
<#
.SYNOPSIS
Sets the default DbContext to use.
.DESCRIPTION
Sets the default DbContext to use.
.PARAMETER Context
Specifies the DbContext to use.
.PARAMETER Project
Specifies the project to use. If omitted, the default project is used.
.PARAMETER StartupProject
Specifies the startup project to use. If omitted, the solution's startup project is used.
.PARAMETER Environment
Specifies the environment to use. If omitted, "Development" is used.
.LINK
about_EntityFramework
#>
function Use-DbContext {
[CmdletBinding(PositionalBinding = $false)]
param ([Parameter(Position = 0, Mandatory = $true)] [string] $Context, [string] $Project, [string] $StartupProject, [string] $Environment)
$dteProject = GetProject $Project
$dteStartupProject = GetStartupProject $StartupProject $dteProject
if (IsDotNetProject $dteProject) {
$contextTypes = GetContextTypes $Project $StartupProject $Environment
$candidates = $contextTypes | ? { $_ -ilike "*$Context" }
$exactMatch = $contextTypes | ? { $_ -eq $Context }
if ($candidates.length -gt 1 -and $exactMatch -is "String") {
$candidates = $exactMatch
}
if ($candidates.length -lt 1) {
throw "No DbContext named '$Context' was found"
} elseif ($candidates.length -gt 1 -and !($candidates -is "String")) {
throw "More than one DbContext named '$Context' was found. Specify which one to use by providing its fully qualified name."
}
$contextTypeName=$candidates
} else {
$contextTypeName = InvokeOperation $dteStartupProject $Environment $dteProject GetContextType @{ name = $Context }
}
$EFDefaultParameterValues.ContextTypeName = $contextTypeName
$EFDefaultParameterValues.ProjectName = $dteProject.ProjectName
}
#
# Add-Migration
#
Register-TabExpansion Add-Migration @{
Context = { param ($tabExpansionContext) GetContextTypes $tabExpansionContext.Project $tabExpansionContext.StartupProject $tabExpansionContext.Environment }
Project = { GetProjects }
StartupProject = { GetProjects }
# disables tab completion on output dir
OutputDir = { }
}
<#
.SYNOPSIS
Adds a new migration.
.DESCRIPTION
Adds a new migration.
.PARAMETER Name
Specifies the name of the migration.
.PARAMETER OutputDir
The directory (and sub-namespace) to use. If omitted, "Migrations" is used. Relative paths are relative to project directory.
.PARAMETER Context
Specifies the DbContext to use. If omitted, the default DbContext is used.
.PARAMETER Project
Specifies the project to use. If omitted, the default project is used.
.PARAMETER StartupProject
Specifies the startup project to use. If omitted, the solution's startup project is used.
.PARAMETER Environment
Specifies the environment to use. If omitted, "Development" is used.
.LINK
Remove-Migration
Update-Database
about_EntityFramework
#>
function Add-Migration {
[CmdletBinding(PositionalBinding = $false)]
param (
[Parameter(Position = 0, Mandatory = $true)]
[string] $Name,
[string] $OutputDir,
[string] $Context,
[string] $Project,
[string] $StartupProject,
[string] $Environment)
$values = ProcessCommonParameters $StartupProject $Project $Context
$dteStartupProject = $values.StartupProject
$dteProject = $values.Project
$contextTypeName = $values.ContextTypeName
if (IsDotNetProject $dteProject) {
$options = ProcessCommonDotnetParameters $dteProject $dteStartupProject $Environment $contextTypeName
if($OutputDir) {
$options += "--output-dir", (NormalizePath $OutputDir)
}
$files = InvokeDotNetEf $dteProject -json migrations add $Name @options
$DTE.ItemOperations.OpenFile($files.MigrationFile) | Out-Null
}
else {
$artifacts = InvokeOperation $dteStartupProject $Environment $dteProject AddMigration @{
name = $Name
outputDir = $OutputDir
contextType = $contextTypeName
}
$dteProject.ProjectItems.AddFromFile($artifacts.MigrationFile) | Out-Null
try {
$dteProject.ProjectItems.AddFromFile($artifacts.MetadataFile) | Out-Null
} catch {
# in some SKUs the call to add MigrationFile will automatically add the MetadataFile because it is named ".Designer.cs"
# this will throw a non fatal error when -OutputDir is outside the main project directory
}
$dteProject.ProjectItems.AddFromFile($artifacts.SnapshotFile) | Out-Null
$DTE.ItemOperations.OpenFile($artifacts.MigrationFile) | Out-Null
ShowConsole
}
Write-Output 'To undo this action, use Remove-Migration.'
}
#
# Update-Database
#
Register-TabExpansion Update-Database @{
Migration = { param ($tabExpansionContext) GetMigrations $tabExpansionContext.Context $tabExpansionContext.Project $tabExpansionContext.StartupProject $tabExpansionContext.Environment }
Context = { param ($tabExpansionContext) GetContextTypes $tabExpansionContext.Project $tabExpansionContext.StartupProject $tabExpansionContext.Environment }
Project = { GetProjects }
StartupProject = { GetProjects }
}
<#
.SYNOPSIS
Updates the database to a specified migration.
.DESCRIPTION
Updates the database to a specified migration.
.PARAMETER Migration
Specifies the target migration. If '0', all migrations will be reverted. If omitted, all pending migrations will be applied.
.PARAMETER Context
Specifies the DbContext to use. If omitted, the default DbContext is used.
.PARAMETER Project
Specifies the project to use. If omitted, the default project is used.
.PARAMETER StartupProject
Specifies the startup project to use. If omitted, the solution's startup project is used.
.PARAMETER Environment
Specifies the environment to use. If omitted, "Development" is used.
.LINK
Script-Migration
about_EntityFramework
#>
function Update-Database {
[CmdletBinding(PositionalBinding = $false)]
param (
[Parameter(Position = 0)]
[string] $Migration,
[string] $Context,
[string] $Project,
[string] $StartupProject,
[string] $Environment)
$values = ProcessCommonParameters $StartupProject $Project $Context
$dteStartupProject = $values.StartupProject
$dteProject = $values.Project
$contextTypeName = $values.ContextTypeName
if (IsDotNetProject $dteProject) {
$options = ProcessCommonDotnetParameters $dteProject $dteStartupProject $Environment $contextTypeName
InvokeDotNetEf $dteProject database update $Migration @options | Out-Null
Write-Output "Done."
} else {
if (IsUwpProject $dteProject) {
throw 'Update-Database should not be used with Universal Windows apps. Instead, call DbContext.Database.Migrate() at runtime.'
}
InvokeOperation $dteStartupProject $Environment $dteProject UpdateDatabase @{
targetMigration = $Migration
contextType = $contextTypeName
}
}
}
#
# Apply-Migration (Obsolete)
#
function Apply-Migration {
# TODO: Remove before RTM
throw 'Apply-Migration has been removed. Use Update-Database instead.'
}
#
# Script-Migration
#
Register-TabExpansion Script-Migration @{
From = { param ($tabExpansionContext) GetMigrations $tabExpansionContext.Context $tabExpansionContext.Project $tabExpansionContext.StartupProject $tabExpansionContext.Environment }
To = { param ($tabExpansionContext) GetMigrations $tabExpansionContext.Context $tabExpansionContext.Project $tabExpansionContext.StartupProject $tabExpansionContext.Environment }
Context = { param ($tabExpansionContext) GetContextTypes $tabExpansionContext.Project $tabExpansionContext.StartupProject $tabExpansionContext.Environment }
Project = { GetProjects }
StartupProject = { GetProjects }
}
<#
.SYNOPSIS
Generates a SQL script from migrations.
.DESCRIPTION
Generates a SQL script from migrations.
.PARAMETER From
Specifies the starting migration. If omitted, '0' (the initial database) is used.
.PARAMETER To
Specifies the ending migration. If omitted, the last migration is used.
.PARAMETER Idempotent
Generates an idempotent script that can be used on a database at any migration.
.PARAMETER Context
Specifies the DbContext to use. If omitted, the default DbContext is used.
.PARAMETER Project
Specifies the project to use. If omitted, the default project is used.
.PARAMETER StartupProject
Specifies the startup project to use. If omitted, the solution's startup project is used.
.PARAMETER Environment
Specifies the environment to use. If omitted, "Development" is used.
.LINK
Update-Database
about_EntityFramework
#>
function Script-Migration {
[CmdletBinding(PositionalBinding = $false)]
param (
[Parameter(ParameterSetName = 'WithoutTo')]
[Parameter(ParameterSetName = 'WithTo', Mandatory = $true)]
[string] $From,
[Parameter(ParameterSetName = 'WithTo', Mandatory = $true)]
[string] $To,
[switch] $Idempotent,
[string] $Context,
[string] $Project,
[string] $StartupProject,
[string] $Environment)
$values = ProcessCommonParameters $StartupProject $Project $Context
$dteStartupProject = $values.StartupProject
$dteProject = $values.Project
$contextTypeName = $values.ContextTypeName
$fullPath = GetProperty $dteProject.Properties FullPath
$intermediatePath = if (IsDotNetProject $dteProject) { "obj\Debug\" }
else { GetProperty $dteProject.ConfigurationManager.ActiveConfiguration.Properties IntermediatePath }
$fullIntermediatePath = Join-Path $fullPath $intermediatePath
$fileName = [IO.Path]::GetRandomFileName()
$fileName = [IO.Path]::ChangeExtension($fileName, '.sql')
$scriptFile = Join-Path $fullIntermediatePath $fileName
if (IsDotNetProject $dteProject) {
$options = ProcessCommonDotnetParameters $dteProject $dteStartupProject $Environment $contextTypeName
$options += "--output",$scriptFile
if ($Idempotent) {
$options += ,"--idempotent"
}
InvokeDotNetEf $dteProject migrations script $From $To @options | Out-Null
$DTE.ItemOperations.OpenFile($scriptFile) | Out-Null
} else {
$script = InvokeOperation $dteStartupProject $Environment $dteProject ScriptMigration @{
fromMigration = $From
toMigration = $To
idempotent = [bool]$Idempotent
contextType = $contextTypeName
}
try {
# NOTE: Certain SKUs cannot create new SQL files, including xproj
$window = $DTE.ItemOperations.NewFile('General\Sql File')
$textDocument = $window.Document.Object('TextDocument')
$editPoint = $textDocument.StartPoint.CreateEditPoint()
$editPoint.Insert($script)
}
catch {
$script | Out-File $scriptFile -Encoding utf8
$DTE.ItemOperations.OpenFile($scriptFile) | Out-Null
}
}
ShowConsole
}
#
# Remove-Migration
#
Register-TabExpansion Remove-Migration @{
Context = { param ($tabExpansionContext) GetContextTypes $tabExpansionContext.Project $tabExpansionContext.StartupProject $tabExpansionContext.Environment }
Project = { GetProjects }
StartupProject = { GetProjects }
}
<#
.SYNOPSIS
Removes the last migration.
.DESCRIPTION
Removes the last migration.
.PARAMETER Context
Specifies the DbContext to use. If omitted, the default DbContext is used.
.PARAMETER Project
Specifies the project to use. If omitted, the default project is used.
.PARAMETER StartupProject
Specifies the startup project to use. If omitted, the solution's startup project is used.
.PARAMETER Environment
Specifies the environment to use. If omitted, "Development" is used.
.PARAMETER Force
Removes the last migration without checking the database. If the last migration has been applied to the database, you will need to manually reverse the changes it made.
.LINK
Add-Migration
about_EntityFramework
#>
function Remove-Migration {
[CmdletBinding(PositionalBinding = $false)]
param ([string] $Context, [string] $Project, [string] $StartupProject, [string] $Environment, [switch] $Force)
$values = ProcessCommonParameters $StartupProject $Project $Context
$dteProject = $values.Project
$contextTypeName = $values.ContextTypeName
$dteStartupProject = $values.StartupProject
$forceRemove = $Force -or (IsUwpProject $dteProject)
if (IsDotNetProject $dteProject) {
$options = ProcessCommonDotnetParameters $dteProject $dteStartupProject $Environment $contextTypeName
if ($forceRemove) {
$options += ,"--force"
}
InvokeDotNetEf $dteProject migrations remove @options | Out-Null
Write-Output "Done."
} else {
$filesToRemove = InvokeOperation $dteStartupProject $Environment $dteProject RemoveMigration @{
contextType = $contextTypeName
force = [bool]$forceRemove
}
$filesToRemove | %{
$projectItem = GetProjectItem $dteProject $_
if ($projectItem) {
$projectItem.Remove()
}
}
}
}
#
# Scaffold-DbContext
#
Register-TabExpansion Scaffold-DbContext @{
Provider = { param ($tabExpansionContext) GetProviders $tabExpansionContext.Project }
Project = { GetProjects }
StartupProject = { GetProjects }
}
<#
.SYNOPSIS
Scaffolds a DbContext and entity type classes for a specified database.
.DESCRIPTION
Scaffolds a DbContext and entity type classes for a specified database.
.PARAMETER Connection
Specifies the connection string of the database.
.PARAMETER Provider
Specifies the provider to use. For example, Microsoft.EntityFrameworkCore.SqlServer.
.PARAMETER OutputDir
Specifies the directory to use to output the classes. If omitted, the top-level project directory is used.
.PARAMETER Context
Specifies the name of the generated DbContext class.
.PARAMETER Schemas
Specifies the schemas for which to generate classes.
.PARAMETER Tables
Specifies the tables for which to generate classes.
.PARAMETER DataAnnotations
Use DataAnnotation attributes to configure the model where possible. If omitted, the output code will use only the fluent API.
.PARAMETER Force
Force scaffolding to overwrite existing files. Otherwise, the code will only proceed if no output files would be overwritten.
.PARAMETER Project
Specifies the project to use. If omitted, the default project is used.
.PARAMETER StartupProject
Specifies the startup project to use. If omitted, the solution's startup project is used.
.PARAMETER Environment
Specifies the environment to use. If omitted, "Development" is used.
.LINK
about_EntityFramework
#>
function Scaffold-DbContext {
[CmdletBinding(PositionalBinding = $false)]
param (
[Parameter(Position = 0, Mandatory = $true)]
[string] $Connection,
[Parameter(Position = 1, Mandatory = $true)]
[string] $Provider,
[string] $OutputDir,
[string] $Context,
[string[]] $Schemas = @(),
[string[]] $Tables = @(),
[switch] $DataAnnotations,
[switch] $Force,
[string] $Project,
[string] $StartupProject,
[string] $Environment)
$values = ProcessCommonParameters $StartupProject $Project
$dteStartupProject = $values.StartupProject
$dteProject = $values.Project
if (IsDotNetProject $dteProject) {
$options = ProcessCommonDotnetParameters $dteProject $dteStartupProject $Environment $Context
if ($OutputDir) {
$options += "--output-dir",(NormalizePath $OutputDir)
}
if ($DataAnnotations) {
$options += ,"--data-annotations"
}
if ($Force) {
$options += ,"--force"
}
$options += $Schemas | % { "--schema", $_ }
$options += $Tables | % { "--table", $_ }
InvokeDotNetEf $dteProject dbcontext scaffold $Connection $Provider @options | Out-Null
} else {
$artifacts = InvokeOperation $dteStartupProject $Environment $dteProject ReverseEngineer @{
connectionString = $Connection
provider = $Provider
outputDir = $OutputDir
dbContextClassName = $Context
schemaFilters = $Schemas
tableFilters = $Tables
useDataAnnotations = [bool]$DataAnnotations
overwriteFiles = [bool]$Force
}
$artifacts | %{ $dteProject.ProjectItems.AddFromFile($_) | Out-Null }
$DTE.ItemOperations.OpenFile($artifacts[0]) | Out-Null
ShowConsole
}
}
#
# Enable-Migrations (Obsolete)
#
function Enable-Migrations {
# TODO: Link to some docs on the changes to Migrations
Write-Warning 'Enable-Migrations is obsolete. Use Add-Migration to start using Migrations.'
}
#
# (Private Helpers)
#
function GetProjects {
$projects = Get-Project -All
$groups = $projects | group Name
return $projects | %{
if ($groups | ? Name -eq $_.Name | ? Count -eq 1) {
return $_.Name
}
return $_.ProjectName
}
}
function GetContextTypes($projectName, $startupProjectName, $environment) {
$values = ProcessCommonParameters $startupProjectName $projectName
$startupProject = $values.StartupProject
$project = $values.Project
if (IsDotNetProject $startupProject) {
$options = ProcessCommonDotnetParameters $startupProject $startupProject $environment
$types = InvokeDotNetEf $startupProject -json -skipBuild dbcontext list @options
return $types | %{ $_.fullName }
} else {
$contextTypes = InvokeOperation $startupProject $environment $project GetContextTypes -skipBuild
return $contextTypes | %{ $_.SafeName }
}
}
function GetMigrations($contextTypeName, $projectName, $startupProjectName, $environment) {
$values = ProcessCommonParameters $startupProjectName $projectName $contextTypeName
$startupProject = $values.StartupProject
$project = $values.Project
$contextTypeName = $values.ContextTypeName
if (IsDotNetProject $startupProject) {
$options = ProcessCommonDotnetParameters $startupProject $startupProject $environment $contextTypeName
$migrations = InvokeDotNetEf $startupProject -json -skipBuild migrations list @options
return $migrations | %{ $_.safeName }
}
else {
$migrations = InvokeOperation $startupProject $environment $project GetMigrations @{ contextTypeName = $contextTypeName } -skipBuild
return $migrations | %{ $_.SafeName }
}
}
function ProcessCommonParameters($startupProjectName, $projectName, $contextTypeName) {
$project = GetProject $projectName
if (!$contextTypeName -and $project.ProjectName -eq $EFDefaultParameterValues.ProjectName) {
$contextTypeName = $EFDefaultParameterValues.ContextTypeName
}
$startupProject = GetStartupProject $startupProjectName $project
return @{
Project = $project
ContextTypeName = $contextTypeName
StartupProject = $startupProject
}
}
function NormalizePath($path) {
try {
$pathInfo = Resolve-Path -LiteralPath $path
return $pathInfo.Path.TrimEnd([IO.Path]::DirectorySeparatorChar)
}
catch {
# when directories don't exist yet
return $path.TrimEnd([IO.Path]::DirectorySeparatorChar)
}
}
function ProcessCommonDotnetParameters($dteProject, $dteStartupProject, $Environment, $contextTypeName) {
$options=@()
#if ($dteStartupProject.Name -ne $dteProject.Name) {
# $startupProjectPath = GetProperty $dteStartupProject.Properties FullPath
# $options += "--startup-project",(NormalizePath $startupProjectPath)
#}
if ($Environment) {
$options += "--environment",$Environment
}
if ($contextTypeName) {
$options += "--context",$contextTypeName
}
return $options
}
function IsDotNetProject($project) {
$project.FileName -like "*.xproj"
}
function IsUwpProject($project) {
$targetFrameworkMoniker = GetProperty $project.Properties TargetFrameworkMoniker
$frameworkName = New-Object System.Runtime.Versioning.FrameworkName $targetFrameworkMoniker
return $frameworkName.Identifier -eq '.NETCore'
}
function GetProject($projectName) {
if ($projectName) {
return Get-Project $projectName
}
return Get-Project
}
function ShowConsole {
$componentModel = Get-VSComponentModel
$powerConsoleWindow = $componentModel.GetService([NuGetConsole.IPowerConsoleWindow])
$powerConsoleWindow.Show()
}
function InvokeDotNetEf($project, [switch] $json, [switch] $skipBuild) {
try {
$dotnet = (Get-Command dotnet).Path
} catch {
throw "Could not find .NET Core CLI (dotnet.exe). .NET Core CLI is required to execute EF commands on this project type."
}
Write-Debug "Found $dotnet"
$fullPath = GetProperty $project.Properties FullPath
$projectJson = Join-Path $fullPath project.json
try {
Write-Debug "Reading $projectJson"
$projectDef = Get-Content $projectJson -Raw | ConvertFrom-Json
} catch {
Write-Verbose $_.Exception.Message
throw "Invalid JSON file in $projectJson"
}
if ($projectDef.tools) {
$t=$projectDef.tools | Get-Member Microsoft.EntityFrameworkCore.Tools
}
if (!$t) {
$projectName = $project.ProjectName
throw "Cannot execute this command because 'Microsoft.EntityFrameworkCore.Tools' is not installed in project '$projectName'. Add 'Microsoft.EntityFrameworkCore.Tools' to the 'tools' section in project.json."
}
$output = $null
$config = $project.ConfigurationManager.ActiveConfiguration.ConfigurationName
$arguments = "--configuration", $config
Write-Debug "Using configuration $config"
$buildBasePath = GetProperty $project.ConfigurationManager.ActiveConfiguration.Properties OutputPath
$arguments += "--build-base-path", $buildBasePath
Write-Debug "Using build base path $buildBasePath"
if ($skipBuild) {
$arguments += ,"--no-build"
}
$arguments += $args
# TODO better json output parsing so we don't need to suppress verbose output
if ($json) {
$arguments += ,"--json"
}
else {
$arguments += ,"--verbose"
}
$arguments = $arguments | ? { $_ } | % { if ($_ -like '* *') { "'$_'" } else { $_ } }
$command = "ef $($arguments -join ' ')"
try {
Write-Verbose "Working directory: $fullPath"
Push-Location $fullPath
$ErrorActionPreference='SilentlyContinue'
Write-Verbose "Executing command: dotnet $command"
$output = Invoke-Expression "& '$dotnet' $command" -ErrorVariable verboseOutput
$exit = $LASTEXITCODE
Write-Debug "Finish executing command with code $exit"
if ($exit -ne 0) {
if (!($verboseOutput) -and $output) {
# most often occurs when Microsoft.EntityFrameworkCore.Tools didn't install
throw $output
}
throw $verboseOutput
}
$output = $output -join [Environment]::NewLine
Write-Debug $output
if ($json) {
Write-Debug "Parsing json output"
# TODO trim the output of dotnet-build
$match = [regex]::Match($output, "\[|\{")
$output = $output.Substring($match.Index) | ConvertFrom-Json
} else {
Write-Verbose $output
}
# dotnet commands log verbose output to stderr
Write-Verbose $($verboseOutput -join [Environment]::NewLine)
}
finally {
$ErrorActionPreference='Stop'
Pop-Location
}
return $output
}
function InvokeOperation($startupProject, $environment, $project, $operation, $arguments = @{}, [switch] $skipBuild) {
$startupProjectName = $startupProject.ProjectName
Write-Verbose "Using startup project '$startupProjectName'."
$projectName = $project.ProjectName
Write-Verbose "Using project '$projectName'"
$package = Get-Package -ProjectName $startupProjectName | ? Id -eq Microsoft.EntityFrameworkCore.Tools
if (!($package)) {
throw "Cannot execute this command because Microsoft.EntityFrameworkCore.Tools is not installed in the startup project '$startupProjectName'."
}
if (!$skipBuild) {
if (IsUwpProject $startupProject) {
$config = $startupProject.ConfigurationManager.ActiveConfiguration.ConfigurationName
$configProperties = $startupProject.ConfigurationManager.ActiveConfiguration.Properties
$isNative = (GetProperty $configProperties ProjectN.UseDotNetNativeToolchain) -eq 'True'
if ($isNative) {
throw "Cannot run in '$config' mode because 'Compile with the .NET Native tool chain' is enabled. Disable this setting or use a different configuration and try again."
}
}
Write-Verbose 'Build started...'
# TODO: Only build required project. Don't use BuildProject, you can't specify platform
$solutionBuild = $DTE.Solution.SolutionBuild
$solutionBuild.Build($true)
if ($solutionBuild.LastBuildInfo) {
throw "Build failed."
}
Write-Verbose 'Build succeeded.'
}
if (![Type]::GetType('Microsoft.EntityFrameworkCore.Design.OperationResultHandler')) {
Add-Type -Path (Join-Path $PSScriptRoot OperationHandlers.cs) -CompilerParameters (
New-Object CodeDom.Compiler.CompilerParameters -Property @{
CompilerOptions = '/d:NET451'
})
}
$logHandler = New-Object Microsoft.EntityFrameworkCore.Design.OperationLogHandler @(
{ param ($message) Write-Error $message }
{ param ($message) Write-Warning $message }
{ param ($message) Write-Host $message }
{ param ($message) Write-Verbose $message }
{ param ($message) Write-Debug $message }
)
$properties = $project.Properties
$fullPath = GetProperty $properties FullPath
$startupOutputPath = GetProperty $startupProject.ConfigurationManager.ActiveConfiguration.Properties OutputPath
$startupProperties = $startupProject.Properties
$startupFullPath = GetProperty $startupProperties FullPath
$startupTargetDir = Join-Path $startupFullPath $startupOutputPath
$webConfig = GetProjectItem $startupProject 'Web.Config'
$appConfig = GetProjectItem $startupProject 'App.Config'
if ($webConfig) {
$configurationFile = GetProperty $webConfig.Properties FullPath
$dataDirectory = Join-Path $startupFullPath 'App_Data'
}
elseif ($appConfig) {
$configurationFile = GetProperty $appConfig.Properties FullPath
}
Write-Verbose "Using application base '$startupTargetDir'."
$info = New-Object AppDomainSetup -Property @{
ApplicationBase = $startupTargetDir
ShadowCopyFiles = 'true'
}
if ($configurationFile) {
Write-Verbose "Using application configuration '$configurationFile'"
$info.ConfigurationFile = $configurationFile
}
else {
Write-Verbose 'No configuration file found.'
}
$domain = [AppDomain]::CreateDomain('EntityFrameworkDesignDomain', $null, $info)
if ($dataDirectory) {
Write-Verbose "Using data directory '$dataDirectory'"
$domain.SetData('DataDirectory', $dataDirectory)
}
try {
$commandsAssembly = 'Microsoft.EntityFrameworkCore.Tools'
$operationExecutorTypeName = 'Microsoft.EntityFrameworkCore.Design.OperationExecutor'
$targetAssemblyName = GetProperty $properties AssemblyName
$startupAssemblyName = GetProperty $startupProperties AssemblyName
$rootNamespace = GetProperty $properties RootNamespace
$executor = $domain.CreateInstanceAndUnwrap(
$commandsAssembly,
$operationExecutorTypeName,
$false,
0,
$null,
@(
[MarshalByRefObject]$logHandler,
@{
startupTargetName = $startupAssemblyName
targetName = $targetAssemblyName
environment = $environment
projectDir = $fullPath
startupProjectDir = $startupFullPath
rootNamespace = $rootNamespace
}
),
$null,
$null)
$resultHandler = New-Object Microsoft.EntityFrameworkCore.Design.OperationResultHandler
$currentDirectory = [IO.Directory]::GetCurrentDirectory()
Write-Verbose "Using current directory '$startupTargetDir'."
[IO.Directory]::SetCurrentDirectory($startupTargetDir)
try {
$domain.CreateInstance(
$commandsAssembly,
"$operationExecutorTypeName+$operation",
$false,
0,
$null,
($executor, [MarshalByRefObject]$resultHandler, $arguments),
$null,
$null) | Out-Null
}
finally {
[IO.Directory]::SetCurrentDirectory($currentDirectory)
}
}
finally {
[AppDomain]::Unload($domain)
}
if ($resultHandler.ErrorType) {
if ($resultHandler.ErrorType -eq 'Microsoft.EntityFrameworkCore.Design.OperationException') {
Write-Verbose $resultHandler.ErrorStackTrace
}
else {
Write-Host $resultHandler.ErrorStackTrace
}
throw $resultHandler.ErrorMessage
}
if ($resultHandler.HasResult) {
return $resultHandler.Result
}
}
function GetProperty($properties, $propertyName) {
$property = $properties.Item($propertyName)
if (!$property) {
return $null
}
return $property.Value
}
function GetProjectItem($project, $path) {
$fullPath = GetProperty $project.Properties FullPath
if (Split-Path $path -IsAbsolute) {
$path = $path.Substring($fullPath.Length)
}
$itemDirectory = (Split-Path $path -Parent)
$projectItems = $project.ProjectItems
if ($itemDirectory) {
$directories = $itemDirectory.Split('\')
$directories | %{
$projectItems = $projectItems.Item($_).ProjectItems
}
}
$itemName = Split-Path $path -Leaf
try {
return $projectItems.Item($itemName)
}
catch [Exception] {
}
return $null
}
function GetStartUpProject($name, $fallbackProject) {
if ($name) {
if (IsDotNetProject $fallbackProject) {
# this means users specified -StartupProject explicitly
# otherwise, ignore what VS has marked as the "startup project"
# TODO remove warning when https://github.com/aspnet/EntityFramework/issues/5311 is fixed
Write-Warning "'-StartupProject' is not supported on *.xproj projects. This parameter will be ignored."
}
return Get-Project $name
}
$startupProjectPaths = $DTE.Solution.SolutionBuild.StartupProjects
if ($startupProjectPaths) {
if ($startupProjectPaths.Length -eq 1) {
$startupProjectPath = $startupProjectPaths[0]
if (!(Split-Path -IsAbsolute $startupProjectPath)) {
$solutionPath = Split-Path (GetProperty $DTE.Solution.Properties Path)
$startupProjectPath = Join-Path $solutionPath $startupProjectPath -Resolve
}
$startupProject = GetSolutionProjects | ?{
try {
$fullName = $_.FullName
}
catch [NotImplementedException] {
return $false
}
if ($fullName -and $fullName.EndsWith('\')) {
$fullName = $fullName.Substring(0, $fullName.Length - 1)
}
return $fullName -eq $startupProjectPath
}
if ($startupProject) {
return $startupProject
}
Write-Warning "Unable to resolve startup project '$startupProjectPath'."
}
else {
Write-Verbose 'More than one startup project found.'
}
}
else {
Write-Verbose 'No startup project found.'
}
return $fallbackProject
}
function GetSolutionProjects() {
$projects = New-Object System.Collections.Stack
$DTE.Solution.Projects | %{
$projects.Push($_)
}
while ($projects.Count -ne 0) {
$project = $projects.Pop();
# NOTE: This line is similar to doing a "yield return" in C#
$project
if ($project.ProjectItems) {
$project.ProjectItems | ?{ $_.SubProject } | %{
$projects.Push($_.SubProject)
}
}
}
}
function GetProviders($projectName) {
if (!($projectName)) {
$projectName = (Get-Project).ProjectName