Skip to content

Commit 7b1c263

Browse files
committed
Fix missing imports for navigation properties
1 parent 19444cf commit 7b1c263

File tree

1 file changed

+14
-6
lines changed

1 file changed

+14
-6
lines changed

src/EntityFrameworkCore.Scaffolding.Handlebars/HbsCSharpEntityTypeGenerator.cs

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -123,11 +123,11 @@ public override string WriteCode(IEntityType entityType, string @namespace, bool
123123

124124
TemplateData.Add("use-data-annotations", UseDataAnnotations);
125125

126-
GenerateImports(entityType);
126+
GenerateImports(entityType, @namespace);
127127

128128
// TODO: _sb.AppendLine("#nullable disable");
129129
@namespace = _options?.Value?.EnableSchemaFolders == true
130-
? $"{@namespace}.{CSharpHelper.Namespace(entityType.GetSchema())}" : @namespace;
130+
? GetNamespaceForEntity(entityType, @namespace) : @namespace;
131131

132132
TemplateData.Add("namespace", @namespace);
133133

@@ -137,19 +137,27 @@ public override string WriteCode(IEntityType entityType, string @namespace, bool
137137
return output;
138138
}
139139

140+
private string GetNamespaceForEntity(IEntityType entityType, string defaultNamespace)
141+
{
142+
return $"{defaultNamespace}.{CSharpHelper.Namespace(entityType.GetSchema())}";
143+
}
144+
140145
/// <summary>
141146
/// Generate entity type imports.
142147
/// </summary>
143148
/// <param name="entityType">Represents an entity type in an <see cref="T:Microsoft.EntityFrameworkCore.Metadata.IModel" />.</param>
144-
protected virtual void GenerateImports(IEntityType entityType)
149+
/// <param name="defaultNamespace">The namespace containing all other entity model namespaces.</param>
150+
protected virtual void GenerateImports(IEntityType entityType, string defaultNamespace)
145151
{
146152
Check.NotNull(entityType, nameof(entityType));
147153

148154
var imports = new List<Dictionary<string, object>>();
149155

150-
foreach (var ns in entityType.GetProperties()
151-
.SelectMany(p => p.ClrType.GetNamespaces())
152-
.Where(ns => ns != "System" && ns != "System.Collections.Generic")
156+
var simpleNamespaces = entityType.GetProperties().SelectMany(p => p.ClrType.GetNamespaces());
157+
var navigationNamespaces = entityType.GetNavigations().Select(x => GetNamespaceForEntity(x.TargetEntityType, defaultNamespace));
158+
var allNamespaces = simpleNamespaces.Concat(navigationNamespaces);
159+
foreach (var ns in allNamespaces
160+
.Where(ns => ns != "System" && ns != "System.Collections.Generic" && ns != GetNamespaceForEntity(entityType, defaultNamespace))
153161
.Distinct()
154162
.OrderBy(x => x, new NamespaceComparer()))
155163
{

0 commit comments

Comments
 (0)