Skip to content

Commit

Permalink
Support value tuples in CSharpHelper
Browse files Browse the repository at this point in the history
Closes #29383
  • Loading branch information
roji committed Oct 18, 2022
1 parent df614b8 commit a55abfa
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 0 deletions.
38 changes: 38 additions & 0 deletions src/EFCore.Design/Design/Internal/CSharpHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using System.Collections;
using System.Globalization;
using System.Numerics;
using System.Runtime.CompilerServices;
using System.Security;
using System.Text;
using Microsoft.EntityFrameworkCore.Internal;
Expand Down Expand Up @@ -693,6 +694,37 @@ private string Array(Type type, IEnumerable values, bool vertical = false)
return builder.ToString();
}

private string ValueTuple(ITuple tuple)
{
var builder = new StringBuilder();

if (tuple.Length == 1)
{
builder
.Append("ValueTuple.Create(")
.Append(UnknownLiteral(tuple[0]))
.Append(')');

return builder.ToString();
}

builder.Append('(');

for (var i = 0; i < tuple.Length; i++)
{
if (i > 0)
{
builder.Append(", ");
}

builder.Append(UnknownLiteral(tuple[i]));
}

builder.Append(')');

return builder.ToString();
}

/// <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 Expand Up @@ -970,6 +1002,12 @@ public virtual string UnknownLiteral(object? value)
return Array(literalType.GetElementType()!, array);
}

if (value is ITuple tuple
&& value.GetType().FullName?.StartsWith("System.ValueTuple`", StringComparison.Ordinal) == true)
{
return ValueTuple(tuple);
}

var valueType = value.GetType();
if (valueType.IsGenericType && !valueType.IsGenericTypeDefinition)
{
Expand Down
12 changes: 12 additions & 0 deletions test/EFCore.Design.Tests/Design/Internal/CSharpHelperTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,18 @@ public void Literal_works_when_multiline_string()
"multi-line\r\nstring\nwith\r\"",
"\"multi-line\\r\\nstring\\nwith\\r\\\"\"");

[ConditionalFact]
public void Literal_works_when_value_tuple()
=> Literal_works((1, "hello"), "(1, \"hello\")");

[ConditionalFact]
public void Literal_works_when_value_tuple_of_length_1()
=> Literal_works(ValueTuple.Create(1), "ValueTuple.Create(1)");

[ConditionalFact]
public void Literal_works_when_value_tuple_of_length_9()
=> Literal_works((1, 2, 3, 4, 5, 6, 7, 8, 9), "(1, 2, 3, 4, 5, 6, 7, 8, 9)");

[ConditionalFact]
[UseCulture("de-DE")]
public void Literal_works_when_DateTime()
Expand Down

0 comments on commit a55abfa

Please sign in to comment.