Skip to content

Commit

Permalink
Use expressions to represent type mapping code literals
Browse files Browse the repository at this point in the history
Mean that type mappings can support language independent code literals. Only the C#/VB/F# helper needs to be language specific, even for unknown types.

Fixes #13414
  • Loading branch information
ajcvickers committed Oct 2, 2018
1 parent b969be3 commit 909ae96
Show file tree
Hide file tree
Showing 10 changed files with 473 additions and 62 deletions.
99 changes: 95 additions & 4 deletions src/EFCore.Design/Design/Internal/CSharpHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using JetBrains.Annotations;
using Microsoft.EntityFrameworkCore.Internal;
Expand Down Expand Up @@ -195,6 +196,9 @@ public virtual string Lambda(IReadOnlyList<string> properties)
/// directly from your code. This API may change or be removed in future releases.
/// </summary>
public virtual string Reference(Type type)
=> Reference(type, useFullName: false);

private string Reference(Type type, bool useFullName)
{
Check.NotNull(type, nameof(type));

Expand Down Expand Up @@ -236,7 +240,10 @@ public virtual string Reference(Type type)
.Append(".");
}

builder.Append(type.ShortDisplayName());
builder.Append(
useFullName
? type.DisplayName()
: type.ShortDisplayName());

return builder.ToString();
}
Expand Down Expand Up @@ -691,15 +698,99 @@ public virtual string UnknownLiteral(object value)
return Array(array);
}

var literal = _relationalTypeMappingSource.FindMapping(literalType)?.FindCodeLiteral(value, "C#");
if (literal != null)
var mapping = _relationalTypeMappingSource.FindMapping(literalType);
if (mapping != null)
{
return literal;
var builder = new StringBuilder();
var expression = mapping.GenerateLiteralExpression(value);
var handled = HandleExpression(expression, builder);

if (!handled)
{
throw new NotSupportedException(
DesignStrings.LiteralExpressionNotSupported(
expression.ToString(),
literalType.ShortDisplayName()));
}

return builder.ToString();
}

throw new InvalidOperationException(DesignStrings.UnknownLiteral(literalType));
}

private bool HandleExpression(Expression expression, StringBuilder builder)
{
// Only handle trivially simple cases for `new` and factory methods
switch (expression.NodeType)
{
case ExpressionType.Convert:
builder
.Append('(')
.Append(Reference(expression.Type))
.Append(')');

return HandleExpression(((UnaryExpression)expression).Operand, builder);
case ExpressionType.New:
builder
.Append("new ")
.Append(Reference(expression.Type, useFullName: true));

return HandleArguments(((NewExpression)expression).Arguments, builder);
case ExpressionType.Call:
{
var callExpression = (MethodCallExpression)expression;
if (callExpression.Method.IsStatic)
{
builder
.Append(Reference(expression.Type, useFullName: true));
}
else
{
if (!HandleExpression(callExpression.Object, builder))
{
return false;
}
}

builder
.Append('.')
.Append(callExpression.Method.Name);

return HandleArguments(callExpression.Arguments, builder);
}
case ExpressionType.Constant:
builder
.Append(UnknownLiteral(((ConstantExpression)expression).Value));

return true;
}

return false;
}

private bool HandleArguments(IEnumerable<Expression> argumentExpressions, StringBuilder builder)
{
builder.Append('(');

var separator = string.Empty;
foreach (var expression in argumentExpressions)
{
builder.Append(separator);

if (!HandleExpression(expression, builder))
{
return false;
}

separator = ", ";
}

builder.Append(')');

return true;
}

/// <summary>
/// This API supports the Entity Framework Core infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
Expand Down
8 changes: 8 additions & 0 deletions src/EFCore.Design/Properties/DesignStrings.Designer.cs

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

57 changes: 30 additions & 27 deletions src/EFCore.Design/Properties/DesignStrings.resx
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
Expand All @@ -26,36 +26,36 @@
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
Expand Down Expand Up @@ -177,6 +177,9 @@
<data name="UnknownLiteral" xml:space="preserve">
<value>The current CSharpHelper cannot scaffold literals of type '{literalType}'. Configure your services to use one that can.</value>
</data>
<data name="LiteralExpressionNotSupported" xml:space="preserve">
<value>The literal expression '{expression}' for '{type}' cannot be parsed. Only simple constructor calls and factory methods are supported.</value>
</data>
<data name="CannotFindRuntimeProviderAssembly" xml:space="preserve">
<value>Unable to find provider assembly with name {assemblyName}. Ensure the specified name is correct and is referenced by the project.</value>
</data>
Expand Down
30 changes: 16 additions & 14 deletions src/EFCore.Relational/Storage/RelationalGeometryTypeMapping.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
using System.Linq.Expressions;
using JetBrains.Annotations;
using Microsoft.EntityFrameworkCore.ChangeTracking;
using Microsoft.EntityFrameworkCore.Internal;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Remotion.Linq.Parsing.ExpressionVisitors;

Expand Down Expand Up @@ -106,28 +105,31 @@ public override Expression AddCustomConversion(Expression expression)
}

/// <summary>
/// Attempts generation of a code (e.g. C#) literal for the given value.
/// Creates a an expression tree that can be used to generate code for the literal value.
/// Currently, only very basic expressions such as constructor calls and factory methods taking
/// simple constants are supported.
/// </summary>
/// <param name="value"> The value for which a literal is needed. </param>
/// <param name="language"> The language, for example "C#". </param>
/// <returns> The generated literal, or <c>null</c> if a literal could not be generated. </returns>
public override string FindCodeLiteral(object value, string language)
{
var geometryText = AsText(value);
/// <returns> An expression tree that can be used to generate code for the literal value. </returns>
public override Expression GenerateLiteralExpression(object value)
=> Expression.Convert(
Expression.Call(
Expression.New(WKTReaderType),
WKTReaderType.GetMethod("Read", new[] { typeof(string) }),
Expression.Constant(AsText(value), typeof(string))),
value.GetType());

// TODO: Allow additional namespaces needed to be put in using directives
return geometryText != null
&& language.Equals("C#", StringComparison.OrdinalIgnoreCase)
? $"({value.GetType().ShortDisplayName()})new NetTopologySuite.IO.WKTReader().Read(\"{geometryText}\")"
: null;
}
/// <summary>
/// The type of the NTS 'WKTReader'.
/// </summary>
protected abstract Type WKTReaderType { get; }

/// <summary>
/// Returns the Well-Known-Text (WKT) representation of the given object, or <c>null</c>
/// if the object is not an 'IGeometry'.
/// </summary>
/// <param name="value"> The value. </param>
/// <returns> The WKT. </returns>
protected abstract string AsText(object value);
protected abstract string AsText([NotNull] object value);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -90,10 +90,6 @@ public override MethodInfo GetDataReaderMethod()
protected override string AsText(object value)
{
var geometry = (IGeometry)value;
if (geometry == null)
{
return null;
}

var srid = geometry.SRID;

Expand All @@ -106,6 +102,13 @@ protected override string AsText(object value)
return text;
}


/// <summary>
/// This API supports the Entity Framework Core infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
/// </summary>
protected override Type WKTReaderType => typeof(WKTReader);

private static SqlServerSpatialReader CreateReader(IGeometryServices services, bool isGeography)
=> new SqlServerSpatialReader(services) { IsGeography = isGeography };

Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
// 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 System.Data.Common;
using System.Globalization;
using System.Reflection;
using GeoAPI;
using GeoAPI.Geometries;
Expand Down Expand Up @@ -81,10 +81,6 @@ public override MethodInfo GetDataReaderMethod()
protected override string AsText(object value)
{
var geometry = (IGeometry)value;
if (geometry == null)
{
return null;
}

var srid = geometry.SRID;

Expand All @@ -97,6 +93,12 @@ protected override string AsText(object value)
return text;
}

/// <summary>
/// This API supports the Entity Framework Core infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
/// </summary>
protected override Type WKTReaderType => typeof(WKTReader);

private static GaiaGeoReader CreateReader(IGeometryServices geometryServices)
=> new GaiaGeoReader(
geometryServices.DefaultCoordinateSequenceFactory,
Expand Down
8 changes: 8 additions & 0 deletions src/EFCore/Properties/CoreStrings.Designer.cs

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/Properties/CoreStrings.resx
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,9 @@
<data name="StillUsingTypeMapper" xml:space="preserve">
<value>The application or database provider is using an Obsolete TypeMapper API even after the provider has implemented a TypeMappingSource. The code must be updated to use the non-obsolete replacement APIs, as indicated by the Obsolete compiler warnings.</value>
</data>
<data name="LiteralGenerationNotSupported" xml:space="preserve">
<value>The type mapping for '{type}' has not implemented code literal generation.</value>
</data>
<data name="InvalidPropertiesExpression" xml:space="preserve">
<value>The properties expression '{expression}' is not valid. The expression should represent a simple property access: 't =&gt; t.MyProperty'. When specifying multiple properties use an anonymous type: 't =&gt; new {{ t.MyProperty1, t.MyProperty2 }}'.</value>
</data>
Expand Down
Loading

0 comments on commit 909ae96

Please sign in to comment.