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

Support Precision Attribute #23424

Merged
merged 4 commits into from
Dec 12, 2020
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
62 changes: 62 additions & 0 deletions src/EFCore.Abstractions/PrecisionAttribute.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
// 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;
using Microsoft.EntityFrameworkCore.Diagnostics;

namespace Microsoft.EntityFrameworkCore
{
/// <summary>
/// Configures the precision of data that is allowed in this property.
/// For example, if the property is a <see cref="decimal" />
/// then this is the maximum number of digits.
/// </summary>
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
public class PrecisionAttribute : Attribute
{
/// <summary>
/// Initializes a new instance of the <see cref="PrecisionAttribute" /> class.
/// </summary>
/// <param name="precision"> The precision of the property. </param>
/// <param name="scale"> The scale of the property. </param>
public PrecisionAttribute(int precision, int scale)
{
if (precision < 0)
{
throw new ArgumentException(AbstractionsStrings.ArgumentIsNegativeNumber(nameof(precision)));
}

if (scale < 0)
{
throw new ArgumentException(AbstractionsStrings.ArgumentIsNegativeNumber(nameof(scale)));
}

Precision = precision;
Scale = scale;
RaymondHuy marked this conversation as resolved.
Show resolved Hide resolved
}

/// <summary>
/// Initializes a new instance of the <see cref="PrecisionAttribute" /> class.
/// </summary>
/// <param name="precision"> The precision of the property. </param>
public PrecisionAttribute(int precision)
{
if (precision < 0)
{
throw new ArgumentException(AbstractionsStrings.ArgumentIsNegativeNumber(nameof(precision)));
}

Precision = precision;
}

/// <summary>
/// The precision of the property.
/// </summary>
public int Precision { get; }

/// <summary>
/// The scale of the property.
/// </summary>
public int? Scale { get; }
}
}

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions src/EFCore.Abstractions/Properties/AbstractionsStrings.resx
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,9 @@
<data name="ArgumentIsEmpty" xml:space="preserve">
<value>The string argument '{argumentName}' cannot be empty.</value>
</data>
<data name="ArgumentIsNegativeNumber" xml:space="preserve">
<value>The number argument '{argumentName}' cannot be negative number.</value>
</data>
<data name="CollectionArgumentHasEmptyElements" xml:space="preserve">
<value>The collection argument '{argumentName}' must not contain any empty elements.</value>
</data>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -595,25 +595,25 @@ private void GenerateProperty(IProperty property, bool useDataAnnotations)
lines.Add(
$".{nameof(PropertyBuilder.HasMaxLength)}({_code.Literal(maxLength.Value)})");
}
}

var precision = property.GetPrecision();
var scale = property.GetScale();
if (precision != null && scale != null && scale != 0)
{
lines.Add(
$".{nameof(PropertyBuilder.HasPrecision)}({_code.Literal(precision.Value)}, {_code.Literal(scale.Value)})");
}
else if (precision != null)
{
lines.Add(
$".{nameof(PropertyBuilder.HasPrecision)}({_code.Literal(precision.Value)})");
}
var precision = property.GetPrecision();
var scale = property.GetScale();
if (precision != null && scale != null && scale != 0)
{
lines.Add(
$".{nameof(PropertyBuilder.HasPrecision)}({_code.Literal(precision.Value)}, {_code.Literal(scale.Value)})");
}
else if (precision != null)
{
lines.Add(
$".{nameof(PropertyBuilder.HasPrecision)}({_code.Literal(precision.Value)})");
}

if (property.IsUnicode() != null)
{
lines.Add(
$".{nameof(PropertyBuilder.IsUnicode)}({(property.IsUnicode() == false ? "false" : "")})");
if (property.IsUnicode() != null)
{
lines.Add(
$".{nameof(PropertyBuilder.IsUnicode)}({(property.IsUnicode() == false ? "false" : "")})");
}
}

var defaultValue = property.GetDefaultValue();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -293,6 +293,7 @@ protected virtual void GeneratePropertyDataAnnotations([NotNull] IProperty prope
GenerateColumnAttribute(property);
GenerateMaxLengthAttribute(property);
GenerateUnicodeAttribute(property);
GeneratePrecisionAttribute(property);

var annotations = _annotationCodeGenerator
.FilterIgnoredAnnotations(property.GetAnnotations())
Expand Down Expand Up @@ -390,6 +391,24 @@ private void GenerateUnicodeAttribute(IProperty property)
}
}

private void GeneratePrecisionAttribute(IProperty property)
{
var precision = property.GetPrecision();
if (precision.HasValue)
{
var precisionAttribute = new AttributeWriter(nameof(PrecisionAttribute));
precisionAttribute.AddParameter(_code.Literal(precision.Value));

var scale = property.GetScale();
if (scale.HasValue)
{
precisionAttribute.AddParameter(_code.Literal(scale.Value));
}

_sb.AppendLine(precisionAttribute.ToString());
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also add a check in CSharpDbContextGenerator.GenerateProperty to avoid adding fluent API calls for precision if data annotations are used

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi @AndriySvyryd I also notice that my previous PR for Unicode Attribute is missing your check suggestion. That PR is already merged so I wonder I could include this small fix in this PR or I will create a new PR for it ? I also notice that there are no test case for checking IsUnicode fluent api to be generated inside https://github.com/dotnet/efcore/blob/main/test/EFCore.Design.Tests/Scaffolding/Internal/CSharpDbContextGeneratorTest.cs

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, include it in this PR

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks @AndriySvyryd I've updated my PR.

}
}

/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
Expand Down
40 changes: 40 additions & 0 deletions src/EFCore/Metadata/Builders/IConventionPropertyBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,46 @@ public interface IConventionPropertyBuilder : IConventionPropertyBaseBuilder
/// <returns> <see langword="true" /> if the capability of persisting unicode characters can be configured for this property. </returns>
bool CanSetIsUnicode(bool? unicode, bool fromDataAnnotation = false);

/// <summary>
/// Configures the precision of the property.
/// </summary>
/// <param name="precision"> The precision of the property. </param>
/// <param name="fromDataAnnotation"> Indicates whether the configuration was specified using a data annotation. </param>
/// <returns>
/// The same builder instance if the configuration was applied,
/// <see langword="null" /> otherwise.
/// </returns>
IConventionPropertyBuilder HasPrecision(int? precision, bool fromDataAnnotation = false);

/// <summary>
/// Returns a value indicating whether the precision of data allowed can be set for this property
/// from the current configuration source.
/// </summary>
/// <param name="precision"> The precision of the property. </param>
/// <param name="fromDataAnnotation"> Indicates whether the configuration was specified using a data annotation. </param>
/// <returns> <see langword="true" /> if the precision of data allowed can be set for this property. </returns>
bool CanSetPrecision(int? precision, bool fromDataAnnotation = false);

/// <summary>
/// Configures the scale of the property.
/// </summary>
/// <param name="scale"> The scale of the property. </param>
/// <param name="fromDataAnnotation"> Indicates whether the configuration was specified using a data annotation. </param>
/// <returns>
/// The same builder instance if the configuration was applied,
/// <see langword="null" /> otherwise.
/// </returns>
IConventionPropertyBuilder HasScale(int? scale, bool fromDataAnnotation = false);

/// <summary>
/// Returns a value indicating whether the scale of data allowed can be set for this property
/// from the current configuration source.
/// </summary>
/// <param name="scale"> The scale of the property. </param>
/// <param name="fromDataAnnotation"> Indicates whether the configuration was specified using a data annotation. </param>
/// <returns> <see langword="true" /> if the scale of data allowed can be set for this property. </returns>
bool CanSetScale(int? scale, bool fromDataAnnotation = false);

/// <summary>
/// Configures whether this property can be modified before the entity is saved to the database.
/// </summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,7 @@ public virtual ConventionSet CreateConventionSet()
var timestampAttributeConvention = new TimestampAttributeConvention(Dependencies);
var backingFieldAttributeConvention = new BackingFieldAttributeConvention(Dependencies);
var unicodeAttributeConvention = new UnicodeAttributeConvention(Dependencies);
var precisionAttributeConvention = new PrecisionAttributeConvention(Dependencies);

conventionSet.PropertyAddedConventions.Add(backingFieldAttributeConvention);
conventionSet.PropertyAddedConventions.Add(backingFieldConvention);
Expand All @@ -128,6 +129,7 @@ public virtual ConventionSet CreateConventionSet()
conventionSet.PropertyAddedConventions.Add(keyDiscoveryConvention);
conventionSet.PropertyAddedConventions.Add(foreignKeyPropertyDiscoveryConvention);
conventionSet.PropertyAddedConventions.Add(unicodeAttributeConvention);
conventionSet.PropertyAddedConventions.Add(precisionAttributeConvention);

conventionSet.EntityTypePrimaryKeyChangedConventions.Add(foreignKeyPropertyDiscoveryConvention);
conventionSet.EntityTypePrimaryKeyChangedConventions.Add(valueGeneratorConvention);
Expand Down
46 changes: 46 additions & 0 deletions src/EFCore/Metadata/Conventions/PrecisionAttributeConvention.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
// 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.Reflection;
using JetBrains.Annotations;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using Microsoft.EntityFrameworkCore.Metadata.Conventions.Infrastructure;

namespace Microsoft.EntityFrameworkCore.Metadata.Conventions
{
/// <summary>
/// A convention that configures the Precision based on the <see cref="PrecisionAttribute" /> applied on the property.
/// </summary>
public class PrecisionAttributeConvention : PropertyAttributeConventionBase<PrecisionAttribute>
{
/// <summary>
/// Creates a new instance of <see cref="PrecisionAttributeConvention" />.
/// </summary>
/// <param name="dependencies"> Parameter object containing dependencies for this convention. </param>
public PrecisionAttributeConvention([NotNull] ProviderConventionSetBuilderDependencies dependencies)
: base(dependencies)
{
}

/// <summary>
/// Called after a property is added to the entity type with an attribute on the associated CLR property or field.
/// </summary>
/// <param name="propertyBuilder"> The builder for the property. </param>
/// <param name="attribute"> The attribute. </param>
/// <param name="clrMember"> The member that has the attribute. </param>
/// <param name="context"> Additional information associated with convention execution. </param>
protected override void ProcessPropertyAdded(
IConventionPropertyBuilder propertyBuilder,
PrecisionAttribute attribute,
MemberInfo clrMember,
IConventionContext context)
{
propertyBuilder.HasPrecision(attribute.Precision, fromDataAnnotation: true);

if (attribute.Scale.HasValue)
{
propertyBuilder.HasScale(attribute.Scale, fromDataAnnotation: true);
}
}
}
}
36 changes: 36 additions & 0 deletions src/EFCore/Metadata/Internal/InternalPropertyBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -858,6 +858,42 @@ IConventionPropertyBuilder IConventionPropertyBuilder.IsUnicode(bool? unicode, b
bool IConventionPropertyBuilder.CanSetIsUnicode(bool? unicode, bool fromDataAnnotation)
=> CanSetIsUnicode(unicode, fromDataAnnotation ? ConfigurationSource.DataAnnotation : ConfigurationSource.Convention);

/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
IConventionPropertyBuilder IConventionPropertyBuilder.HasPrecision(int? precision, bool fromDataAnnotation)
=> HasPrecision(precision, fromDataAnnotation ? ConfigurationSource.DataAnnotation : ConfigurationSource.Convention);

/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
bool IConventionPropertyBuilder.CanSetPrecision(int? precision, bool fromDataAnnotation)
=> CanSetPrecision(precision, fromDataAnnotation ? ConfigurationSource.DataAnnotation : ConfigurationSource.Convention);

/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
IConventionPropertyBuilder IConventionPropertyBuilder.HasScale(int? scale, bool fromDataAnnotation)
=> HasScale(scale, fromDataAnnotation ? ConfigurationSource.DataAnnotation : ConfigurationSource.Convention);

/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
bool IConventionPropertyBuilder.CanSetScale(int? scale, bool fromDataAnnotation)
=> CanSetScale(scale, fromDataAnnotation ? ConfigurationSource.DataAnnotation : ConfigurationSource.Convention);

/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -375,6 +375,28 @@ public void ComputedColumnSql_works()
});
}

[ConditionalFact]
public void IsUnicode_works()
{
Test(
modelBuilder => {
modelBuilder.Entity("Entity").Property<string>("UnicodeColumn").IsUnicode();
modelBuilder.Entity("Entity").Property<string>("NonUnicodeColumn").IsUnicode(false);
},
new ModelCodeGenerationOptions(),
code => {
Assert.Contains("Property(e => e.UnicodeColumn).IsUnicode()", code.ContextFile.Code);
Assert.Contains("Property(e => e.NonUnicodeColumn).IsUnicode(false)", code.ContextFile.Code);
},
model =>
{
var entity = model.FindEntityType("TestNamespace.Entity");
Assert.True(entity.GetProperty("UnicodeColumn").IsUnicode());
Assert.False(entity.GetProperty("NonUnicodeColumn").IsUnicode());
});
}


[ConditionalFact]
public void ComputedColumnSql_works_stored()
{
Expand Down
Loading