Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

RevEng: Pass in correct arguments to ScaffoldingTypeMapper #9094

Merged
merged 1 commit into from
Jul 7, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 15 additions & 7 deletions src/EFCore.Design/Scaffolding/Internal/CSharpDbContextGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ public virtual string WriteCode(
GenerateClass(model, contextName, connectionString, useDataAnnotations);
}

_sb.Append("}");
_sb.AppendLine("}");

return _sb.ToString();
}
Expand Down Expand Up @@ -428,8 +428,7 @@ private void GenerateIndex(IIndex index)

var annotations = index.GetAnnotations().ToList();

if (!string.IsNullOrEmpty(index.Relational().Name)
&& index.Relational().Name != ConstraintNamer.GetDefaultName(index))
if (!string.IsNullOrEmpty((string)index[RelationalAnnotationNames.Name]))
{
lines.Add($".{nameof(RelationalIndexBuilderExtensions.HasName)}({_cSharpUtilities.DelimitString(index.Relational().Name)})");
RemoveAnnotation(ref annotations, RelationalAnnotationNames.Name);
Expand Down Expand Up @@ -542,6 +541,7 @@ private void GenerateProperty(IProperty property, bool useDataAnnotations)
}

var valueGenerated = property.ValueGenerated;
var isRowVersion = false;
if (((Property)property).GetValueGeneratedConfigurationSource().HasValue
&& new RelationalValueGeneratorConvention().GetValueGenerated((Property)property) != valueGenerated)
{
Expand All @@ -553,7 +553,10 @@ private void GenerateProperty(IProperty property, bool useDataAnnotations)
break;

case ValueGenerated.OnAddOrUpdate:
methodName = nameof(PropertyBuilder.ValueGeneratedOnAddOrUpdate);
isRowVersion = property.IsConcurrencyToken;
methodName = isRowVersion
? nameof(PropertyBuilder.IsRowVersion)
: nameof(PropertyBuilder.ValueGeneratedOnAddOrUpdate);
break;

case ValueGenerated.Never:
Expand All @@ -568,6 +571,12 @@ private void GenerateProperty(IProperty property, bool useDataAnnotations)
lines.Add($".{methodName}()");
}

if (property.IsConcurrencyToken
&& !isRowVersion)
{
lines.Add($".{nameof(PropertyBuilder.IsConcurrencyToken)}()");
}

var annotationsToRemove = new List<IAnnotation>();

foreach (var annotation in annotations)
Expand Down Expand Up @@ -639,12 +648,11 @@ private void GenerateRelationship(IForeignKey foreignKey, bool useDataAnnotation
lines.Add($".{nameof(ReferenceReferenceBuilder.OnDelete)}({_cSharpUtilities.GenerateLiteral(foreignKey.DeleteBehavior)})");
}

RemoveAnnotation(ref annotations, RelationalAnnotationNames.Name);

if (foreignKey.Relational().Name != ConstraintNamer.GetDefaultName(foreignKey))
if (!string.IsNullOrEmpty((string)foreignKey[RelationalAnnotationNames.Name]))
{
canUseDataAnnotations = false;
lines.Add($".{nameof(RelationalReferenceReferenceBuilderExtensions.HasConstraintName)}({_cSharpUtilities.DelimitString(foreignKey.Relational().Name)})");
RemoveAnnotation(ref annotations, RelationalAnnotationNames.Name);
}

var annotationsToRemove = new List<IAnnotation>();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,6 @@ public class RelationalScaffoldingModelFactory : IScaffoldingModelFactory
internal const string NavigationNameUniquifyingPattern = "{0}Navigation";
internal const string SelfReferencingPrincipalEndNavigationNamePattern = "Inverse{0}";


protected virtual IOperationReporter Reporter { get; }
protected virtual IRelationalTypeMapper TypeMapper { get; }
protected virtual ICandidateNamingService CandidateNamingService { get; }
Expand All @@ -40,7 +39,6 @@ public class RelationalScaffoldingModelFactory : IScaffoldingModelFactory
private readonly IDatabaseModelFactory _databaseModelFactory;
private readonly HashSet<DatabaseColumn> _unmappedColumns = new HashSet<DatabaseColumn>();
private readonly IPluralizer _pluralizer;
private readonly IScaffoldingProviderCodeGenerator _providerCodeGenerator;
private readonly ICSharpUtilities _cSharpUtilities;
private readonly IScaffoldingTypeMapper _scaffoldingTypeMapper;

Expand All @@ -50,7 +48,6 @@ public RelationalScaffoldingModelFactory(
[NotNull] IDatabaseModelFactory databaseModelFactory,
[NotNull] ICandidateNamingService candidateNamingService,
[NotNull] IPluralizer pluralizer,
[NotNull] IScaffoldingProviderCodeGenerator providerCodeGenerator,
[NotNull] ICSharpUtilities cSharpUtilities,
[NotNull] IScaffoldingTypeMapper scaffoldingTypeMapper)
{
Expand All @@ -59,7 +56,6 @@ public RelationalScaffoldingModelFactory(
Check.NotNull(databaseModelFactory, nameof(databaseModelFactory));
Check.NotNull(candidateNamingService, nameof(candidateNamingService));
Check.NotNull(pluralizer, nameof(pluralizer));
Check.NotNull(providerCodeGenerator, nameof(providerCodeGenerator));
Check.NotNull(cSharpUtilities, nameof(cSharpUtilities));
Check.NotNull(scaffoldingTypeMapper, nameof(scaffoldingTypeMapper));

Expand All @@ -68,7 +64,6 @@ public RelationalScaffoldingModelFactory(
CandidateNamingService = candidateNamingService;
_databaseModelFactory = databaseModelFactory;
_pluralizer = pluralizer;
_providerCodeGenerator = providerCodeGenerator;
_cSharpUtilities = cSharpUtilities;
_scaffoldingTypeMapper = scaffoldingTypeMapper;
}
Expand Down Expand Up @@ -143,7 +138,7 @@ protected virtual string GetPropertyName([NotNull] DatabaseColumn column)
c => CandidateNamingService.GenerateCandidateIdentifier(c.Name),
usedNames,
_cSharpUtilities,
null));
singularizePluralizer: null));
}

return _columnNamers[table].GetName(column);
Expand Down Expand Up @@ -336,7 +331,8 @@ protected virtual PropertyBuilder VisitColumn([NotNull] EntityTypeBuilder builde

property.HasColumnName(column.Name);

if (!typeScaffoldingInfo.IsInferred && !string.IsNullOrWhiteSpace(column.StoreType))
if (!typeScaffoldingInfo.IsInferred
&& !string.IsNullOrWhiteSpace(column.StoreType))
{
property.HasColumnType(column.StoreType);
}
Expand Down Expand Up @@ -376,15 +372,22 @@ protected virtual PropertyBuilder VisitColumn([NotNull] EntityTypeBuilder builde
property.HasComputedColumnSql(column.ComputedColumnSql);
}

if (!((column.Table.PrimaryKey?.Columns.Contains(column)) ?? false))
if (!(column.Table.PrimaryKey?.Columns.Contains(column) ?? false))
{
property.IsRequired(!column.IsNullable && !forceNullable);
}

if ((bool?)column[ScaffoldingAnnotationNames.ConcurrencyToken] == true)
{
property.IsConcurrencyToken();
}

property.Metadata.Scaffolding().ColumnOrdinal = column.Table.Columns.IndexOf(column);

property.Metadata.AddAnnotations(
column.GetAnnotations().Where(a => a.Name != ScaffoldingAnnotationNames.UnderlyingStoreType));
column.GetAnnotations().Where(
a => a.Name != ScaffoldingAnnotationNames.UnderlyingStoreType
&& a.Name != ScaffoldingAnnotationNames.ConcurrencyToken));

return property;
}
Expand Down Expand Up @@ -470,7 +473,6 @@ protected virtual IndexBuilder VisitUniqueConstraint([NotNull] EntityTypeBuilder
var propertyNames = uniqueConstraint.Columns.Select(GetPropertyName).ToArray();
var indexBuilder = builder.HasIndex(propertyNames).IsUnique();


if (!string.IsNullOrEmpty(uniqueConstraint.Name))
{
indexBuilder.HasName(uniqueConstraint.Name);
Expand All @@ -479,7 +481,6 @@ protected virtual IndexBuilder VisitUniqueConstraint([NotNull] EntityTypeBuilder
indexBuilder.Metadata.AddAnnotations(uniqueConstraint.GetAnnotations());

return indexBuilder;

}

protected virtual EntityTypeBuilder VisitIndexes([NotNull] EntityTypeBuilder builder, [NotNull] ICollection<DatabaseIndex> indexes)
Expand Down Expand Up @@ -522,7 +523,8 @@ protected virtual IndexBuilder VisitIndex([NotNull] EntityTypeBuilder builder, [
indexBuilder.HasFilter(index.Filter);
}

if (!string.IsNullOrEmpty(index.Name))
if (!string.IsNullOrEmpty(index.Name)
&& index.Name != ConstraintNamer.GetDefaultName(indexBuilder.Metadata))
{
indexBuilder.HasName(index.Name);
}
Expand Down Expand Up @@ -591,7 +593,7 @@ protected virtual IMutableForeignKey VisitForeignKey([NotNull] ModelBuilder mode
}

var dependentProperties = foreignKey.Columns
.Select(fc => GetPropertyName(fc))
.Select(GetPropertyName)
.Select(name => dependentEntityType.FindProperty(name))
.ToList()
.AsReadOnly();
Expand Down Expand Up @@ -621,7 +623,7 @@ protected virtual IMutableForeignKey VisitForeignKey([NotNull] ModelBuilder mode

var principalPropertiesMap = foreignKey.PrincipalColumns
.Select(
fc => (property: principalEntityType.FindProperty(GetPropertyName(fc)), column: fc));
fc => (property: principalEntityType.FindProperty(GetPropertyName(fc)), column: fc)).ToList();
var principalProperties = principalPropertiesMap
.Select(tuple => tuple.property)
.ToList();
Expand All @@ -636,7 +638,7 @@ protected virtual IMutableForeignKey VisitForeignKey([NotNull] ModelBuilder mode
// ensure all principal properties are non-nullable even if the columns
// are nullable on the database. EF's concept of a key requires this.
var nullablePrincipalProperties =
principalPropertiesMap.Where(tuple => tuple.property.IsNullable);
principalPropertiesMap.Where(tuple => tuple.property.IsNullable).ToList();
if (nullablePrincipalProperties.Any())
{
Reporter.WriteWarning(
Expand Down Expand Up @@ -672,9 +674,13 @@ protected virtual IMutableForeignKey VisitForeignKey([NotNull] ModelBuilder mode
var dependentKey = dependentEntityType.FindKey(dependentProperties);
var dependentIndex = dependentEntityType.FindIndex(dependentProperties);
key.IsUnique = dependentKey != null
|| (dependentIndex != null && dependentIndex.IsUnique);
|| dependentIndex != null && dependentIndex.IsUnique;

key.Relational().Name = foreignKey.Name;
if (!string.IsNullOrEmpty(foreignKey.Name)
&& foreignKey.Name != ConstraintNamer.GetDefaultName(key))
{
key.Relational().Name = foreignKey.Name;
}

AssignOnDeleteAction(foreignKey, key);

Expand All @@ -694,8 +700,8 @@ protected virtual void AddNavigationProperties([NotNull] IMutableForeignKey fore
_cSharpUtilities.GenerateCSharpIdentifier(
dependentEndNavigationPropertyCandidateName,
dependentEndExistingIdentifiers,
null,
NavigationUniquifier);
singularizePluralizer: null,
uniquifier: NavigationUniquifier);

foreignKey.HasDependentToPrincipal(dependentEndNavigationPropertyName);

Expand All @@ -718,8 +724,8 @@ protected virtual void AddNavigationProperties([NotNull] IMutableForeignKey fore
_cSharpUtilities.GenerateCSharpIdentifier(
principalEndNavigationPropertyCandidateName,
principalEndExistingIdentifiers,
null,
NavigationUniquifier);
singularizePluralizer: null,
uniquifier: NavigationUniquifier);

foreignKey.HasPrincipalToDependent(principalEndNavigationPropertyName);
}
Expand Down Expand Up @@ -753,8 +759,9 @@ protected virtual TypeScaffoldingInfo GetTypeScaffoldingInfo([NotNull] DatabaseC

var typeScaffoldingInfo = _scaffoldingTypeMapper.FindMapping(
column.GetUnderlyingStoreType() ?? column.StoreType,
keyOrIndex: false,
rowVersion: false);
column.IsKeyOrIndex(),
column.IsRowVersion());

if (column.GetUnderlyingStoreType() != null)
{
return new TypeScaffoldingInfo(
Expand Down
18 changes: 9 additions & 9 deletions src/EFCore.Design/Scaffolding/Internal/ScaffoldingTypeMapper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ public ScaffoldingTypeMapper([NotNull] IRelationalTypeMapper typeMapper)
protected virtual IRelationalTypeMapper TypeMapper { get; }

public virtual TypeScaffoldingInfo FindMapping(
[NotNull] string storeType,
string storeType,
bool keyOrIndex,
bool rowVersion)
{
Expand All @@ -33,9 +33,9 @@ public virtual TypeScaffoldingInfo FindMapping(
return null;
}

bool canInfer = false;
var canInfer = false;
bool? scaffoldUnicode = null;
int? scaffoldMaxLengh = null;
int? scaffoldMaxLength = null;

if (mapping.ClrType == typeof(byte[])
&& TypeMapper.ByteArrayMapper != null)
Expand All @@ -49,7 +49,7 @@ public virtual TypeScaffoldingInfo FindMapping(

// Check for size
var sizedMapping = TypeMapper.ByteArrayMapper.FindMapping(rowVersion, keyOrIndex, size: null);
scaffoldMaxLengh = sizedMapping.Size != byteArrayMapping.Size ? byteArrayMapping.Size : null;
scaffoldMaxLength = sizedMapping.Size != byteArrayMapping.Size ? byteArrayMapping.Size : null;
}
}
else if (mapping.ClrType == typeof(string)
Expand All @@ -67,8 +67,8 @@ public virtual TypeScaffoldingInfo FindMapping(
scaffoldUnicode = unicodeMapping.IsUnicode != stringMapping.IsUnicode ? (bool?)stringMapping.IsUnicode : null;

// Check for size
var sizedMapping = TypeMapper.StringMapper.FindMapping(unicode: mapping.IsUnicode, keyOrIndex: keyOrIndex, maxLength: null);
scaffoldMaxLengh = sizedMapping.Size != stringMapping.Size ? stringMapping.Size : null;
var sizedMapping = TypeMapper.StringMapper.FindMapping(mapping.IsUnicode, keyOrIndex, maxLength: null);
scaffoldMaxLength = sizedMapping.Size != stringMapping.Size ? stringMapping.Size : null;
}
}
else
Expand All @@ -83,9 +83,9 @@ public virtual TypeScaffoldingInfo FindMapping(

return new TypeScaffoldingInfo(
mapping.ClrType,
inferred: canInfer,
scaffoldUnicode: scaffoldUnicode,
scaffoldMaxLength: scaffoldMaxLengh);
canInfer,
scaffoldUnicode,
scaffoldMaxLength);
}
}
}
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using System.Linq;
using JetBrains.Annotations;
using Microsoft.EntityFrameworkCore.Metadata;

namespace Microsoft.EntityFrameworkCore.Scaffolding.Metadata.Internal
{
Expand All @@ -12,5 +14,33 @@ public static string DisplayName([NotNull] this DatabaseColumn column)
var tablePrefix = column.Table?.DisplayName();
return (!string.IsNullOrEmpty(tablePrefix) ? tablePrefix + "." : "") + column.Name;
}

public static bool IsKeyOrIndex([NotNull] this DatabaseColumn column)
{
var table = column.Table;

if (table.PrimaryKey?.Columns.Contains(column) == true)
{
return true;
}

if (table.UniqueConstraints.Any(uc => uc.Columns.Contains(column)))
{
return true;
}

if (table.Indexes.Any(uc => uc.Columns.Contains(column)))
{
return true;
}

return false;
}

public static bool IsRowVersion([NotNull] this DatabaseColumn column)
{
return column.ValueGenerated == ValueGenerated.OnAddOrUpdate
&& (bool?)column[ScaffoldingAnnotationNames.ConcurrencyToken] == true;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,6 @@ namespace Microsoft.EntityFrameworkCore.Scaffolding.Metadata.Internal
public static class ScaffoldingAnnotationNames
{
public const string UnderlyingStoreType = "UnderlyingStoreType";
public const string ConcurrencyToken = "ConcurrencyToken";
}
}
Loading