Skip to content

Commit

Permalink
Metadata: Add Getter/Setter support for indexed properties
Browse files Browse the repository at this point in the history
Part of #13610
  • Loading branch information
smitpatel committed Dec 31, 2019
1 parent a9c6cb3 commit 9f7ae44
Show file tree
Hide file tree
Showing 15 changed files with 224 additions and 50 deletions.
22 changes: 22 additions & 0 deletions src/EFCore/Extensions/ConventionEntityTypeExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -504,6 +504,28 @@ public static IConventionProperty AddProperty(
bool setTypeConfigurationSource = true, bool fromDataAnnotation = false)
=> entityType.AddProperty(name, propertyType, null, setTypeConfigurationSource, fromDataAnnotation);

/// <summary>
/// Adds an indexed property to this entity type.
/// </summary>
/// <param name="entityType"> The entity type to add the property to. </param>
/// <param name="name"> The name of the property to add. </param>
/// <param name="propertyType"> The type of value the property will hold. </param>
/// <param name="setTypeConfigurationSource"> Indicates whether the type configuration source should be set. </param>
/// <param name="fromDataAnnotation"> Indicates whether the configuration was specified using a data annotation. </param>
/// <returns> The newly created property. </returns>
public static IConventionProperty AddIndexedProperty(
[NotNull] this IConventionEntityType entityType, [NotNull] string name, [NotNull] Type propertyType,
bool setTypeConfigurationSource = true, bool fromDataAnnotation = false)
{
Check.NotNull(entityType, nameof(entityType));

var indexerPropertyInfo = entityType.GetIndexerPropertyInfo();

return indexerPropertyInfo != null
? entityType.AddProperty(name, propertyType, indexerPropertyInfo, setTypeConfigurationSource, fromDataAnnotation)
: null;
}

/// <summary>
/// Gets the index defined on the given property. Returns null if no index is defined.
/// </summary>
Expand Down
24 changes: 24 additions & 0 deletions src/EFCore/Extensions/MutableEntityTypeExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
using System.Linq.Expressions;
using System.Reflection;
using JetBrains.Annotations;
using Microsoft.EntityFrameworkCore.Diagnostics;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using Microsoft.EntityFrameworkCore.Utilities;
Expand Down Expand Up @@ -463,6 +465,28 @@ public static IMutableProperty AddProperty(
[NotNull] this IMutableEntityType entityType, [NotNull] string name, [NotNull] Type propertyType)
=> entityType.AddProperty(name, propertyType, null);

/// <summary>
/// Adds an indexed property to this entity type.
/// </summary>
/// <param name="entityType"> The entity type to add the property to. </param>
/// <param name="name"> The name of the property to add. </param>
/// <param name="propertyType"> The type of value the property will hold. </param>
/// <returns> The newly created property. </returns>
public static IMutableProperty AddIndexedProperty(
[NotNull] this IMutableEntityType entityType, [NotNull] string name, [NotNull] Type propertyType)
{
Check.NotNull(entityType, nameof(entityType));

var indexerPropertyInfo = entityType.GetIndexerPropertyInfo();
if (indexerPropertyInfo == null)
{
throw new InvalidOperationException(
CoreStrings.NonIndexerEntityType(name, entityType.DisplayName(), typeof(string).ShortDisplayName()));
}

return entityType.AddProperty(name, propertyType, indexerPropertyInfo);
}

/// <summary>
/// Gets the index defined on the given property. Returns null if no index is defined.
/// </summary>
Expand Down
17 changes: 17 additions & 0 deletions src/EFCore/Extensions/PropertyBaseExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,23 @@ public static string GetFieldName([NotNull] this IPropertyBase propertyBase)
public static bool IsShadowProperty([NotNull] this IPropertyBase property)
=> Check.NotNull(property, nameof(property)).GetIdentifyingMemberInfo() == null;

/// <summary>
/// Gets a value indicating whether this is an indexer property. An indexer property is one that is accessed through
/// indexer on entity class.
/// </summary>
/// <param name="property"> The property to check. </param>
/// <returns>
/// <c>True</c> if the property is an indexer property, otherwise <c>false</c>.
/// </returns>
public static bool IsIndexerProperty([NotNull] this IPropertyBase property)
{
Check.NotNull(property, nameof(property));

var identifyingMemberInfo = property.GetIdentifyingMemberInfo();

return identifyingMemberInfo != null && identifyingMemberInfo.IsSameAs(property.DeclaringType.GetIndexerPropertyInfo());
}

/// <summary>
/// <para>
/// Gets the <see cref="PropertyAccessMode" /> being used for this property.
Expand Down
2 changes: 1 addition & 1 deletion src/EFCore/Infrastructure/ModelValidator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -783,7 +783,7 @@ protected virtual void ValidateFieldMapping(
.GetDeclaredProperties()
.Cast<IPropertyBase>()
.Concat(entityType.GetDeclaredNavigations())
.Where(p => !p.IsShadowProperty()));
.Where(p => !p.IsShadowProperty() && !p.IsIndexerProperty()));

var constructorBinding = (InstantiationBinding)entityType[CoreAnnotationNames.ConstructorBinding];

Expand Down
12 changes: 10 additions & 2 deletions src/EFCore/Metadata/Internal/ClrPropertyGetterFactory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ protected override IClrPropertyGetter CreateGeneric<TEntity, TValue, TNonNullabl
Expression readExpression;
if (memberInfo.DeclaringType.IsAssignableFrom(typeof(TEntity)))
{
readExpression = Expression.MakeMemberAccess(entityParameter, memberInfo);
readExpression = CreateMemberAccess(entityParameter);
}
else
{
Expand All @@ -57,7 +57,7 @@ protected override IClrPropertyGetter CreateGeneric<TEntity, TValue, TNonNullabl
Expression.Condition(
Expression.ReferenceEqual(converted, Expression.Constant(null)),
Expression.Default(memberInfo.GetMemberType()),
Expression.MakeMemberAccess(converted, memberInfo))
CreateMemberAccess(converted))
});
}

Expand Down Expand Up @@ -101,6 +101,14 @@ protected override IClrPropertyGetter CreateGeneric<TEntity, TValue, TNonNullabl
return new ClrPropertyGetter<TEntity, TValue>(
Expression.Lambda<Func<TEntity, TValue>>(readExpression, entityParameter).Compile(),
Expression.Lambda<Func<TEntity, bool>>(hasDefaultValueExpression, entityParameter).Compile());

Expression CreateMemberAccess(Expression parameter)
{
return propertyBase?.IsIndexerProperty() == true
? Expression.MakeIndex(
entityParameter, (PropertyInfo)memberInfo, new List<Expression>() { Expression.Constant(propertyBase.Name) })
: (Expression)Expression.MakeMemberAccess(parameter, memberInfo);
}
}
}
}
16 changes: 12 additions & 4 deletions src/EFCore/Metadata/Internal/ClrPropertySetterFactory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,7 @@ protected override IClrPropertySetter CreateGeneric<TEntity, TValue, TNonNullabl
Expression writeExpression;
if (memberInfo.DeclaringType.IsAssignableFrom(typeof(TEntity)))
{
writeExpression = Expression.MakeMemberAccess(entityParameter, memberInfo)
.Assign(convertedParameter);
writeExpression = CreateMemberAssignment(entityParameter);
}
else
{
Expand All @@ -62,8 +61,7 @@ protected override IClrPropertySetter CreateGeneric<TEntity, TValue, TNonNullabl
Expression.TypeAs(entityParameter, memberInfo.DeclaringType)),
Expression.IfThen(
Expression.ReferenceNotEqual(converted, Expression.Constant(null)),
Expression.MakeMemberAccess(converted, memberInfo)
.Assign(convertedParameter))
CreateMemberAssignment(converted))
});
}

Expand All @@ -78,6 +76,16 @@ protected override IClrPropertySetter CreateGeneric<TEntity, TValue, TNonNullabl
&& propertyType.UnwrapNullableType().IsEnum
? new NullableEnumClrPropertySetter<TEntity, TValue, TNonNullableEnumValue>(setter)
: (IClrPropertySetter)new ClrPropertySetter<TEntity, TValue>(setter);

Expression CreateMemberAssignment(Expression parameter)
{
return propertyBase?.IsIndexerProperty() == true
? Expression.Assign(
Expression.MakeIndex(
entityParameter, (PropertyInfo)memberInfo, new List<Expression>() { Expression.Constant(propertyBase.Name) }),
convertedParameter)
: Expression.MakeMemberAccess(parameter, memberInfo).Assign(convertedParameter);
}
}
}
}
4 changes: 2 additions & 2 deletions src/EFCore/Metadata/Internal/EntityType.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1599,7 +1599,7 @@ private Type ValidateClrMember(string name, MemberInfo memberInfo, bool throwOnN

if (name != memberInfo.GetSimpleMemberName())
{
if ((memberInfo as PropertyInfo)?.IsEFIndexerProperty() != true)
if ((memberInfo as PropertyInfo)?.IsIndexerProperty() != true)
{
if (throwOnNameMismatch)
{
Expand Down Expand Up @@ -2066,7 +2066,7 @@ public virtual Property AddProperty(

if (memberInfo != null
&& propertyType != memberInfo.GetMemberType()
&& (memberInfo as PropertyInfo)?.IsEFIndexerProperty() != true)
&& (memberInfo as PropertyInfo)?.IsIndexerProperty() != true)
{
if (typeConfigurationSource != null)
{
Expand Down
2 changes: 1 addition & 1 deletion src/EFCore/Metadata/Internal/InternalEntityTypeBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -682,7 +682,7 @@ public virtual bool CanAddProperty([NotNull] Type propertyType, [NotNull] string
var memberInfo = Metadata.ClrType.GetMembersInHierarchy(name).FirstOrDefault();
if (memberInfo != null
&& propertyType != memberInfo.GetMemberType()
&& (memberInfo as PropertyInfo)?.IsEFIndexerProperty() != true
&& (memberInfo as PropertyInfo)?.IsIndexerProperty() != true
&& typeConfigurationSource != null)
{
return false;
Expand Down
25 changes: 25 additions & 0 deletions src/EFCore/Metadata/Internal/TypeBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ public abstract class TypeBase : ConventionAnnotatable, IMutableTypeBase, IConve
private readonly Dictionary<string, ConfigurationSource> _ignoredMembers
= new Dictionary<string, ConfigurationSource>(StringComparer.Ordinal);

private PropertyInfo _indexerPropertyInfo;
private Dictionary<string, PropertyInfo> _runtimeProperties;
private Dictionary<string, FieldInfo> _runtimeFields;

Expand Down Expand Up @@ -168,6 +169,29 @@ public virtual IReadOnlyDictionary<string, FieldInfo> GetRuntimeFields()
return _runtimeFields;
}

/// <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>
public virtual PropertyInfo GetIndexerPropertyInfo()
{
if (ClrType == null)
{
return null;
}

if (_indexerPropertyInfo == null)
{
var indexerPropertyInfo = GetRuntimeProperties().Values.FirstOrDefault(pi => pi.IsIndexerProperty());

Interlocked.CompareExchange(ref _indexerPropertyInfo, indexerPropertyInfo, null);
}

return _indexerPropertyInfo;
}

/// <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 @@ -198,6 +222,7 @@ public virtual void ClearCaches()
{
_runtimeProperties = null;
_runtimeFields = null;
_indexerPropertyInfo = null;
Thread.MemoryBarrier();
}

Expand Down
23 changes: 12 additions & 11 deletions src/EFCore/Metadata/Internal/TypeBaseExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,15 @@ public static IReadOnlyDictionary<string, PropertyInfo> GetRuntimeProperties([No
public static IReadOnlyDictionary<string, FieldInfo> GetRuntimeFields([NotNull] this ITypeBase type)
=> (type as TypeBase).GetRuntimeFields();

/// <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>
public static PropertyInfo GetIndexerPropertyInfo([NotNull] this ITypeBase type)
=> (type as TypeBase).GetIndexerPropertyInfo();

/// <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 All @@ -53,17 +62,9 @@ public static IReadOnlyDictionary<string, FieldInfo> GetRuntimeFields([NotNull]
/// </summary>
public static MemberInfo FindClrMember([NotNull] this TypeBase type, [NotNull] string name)
{
if (type.GetRuntimeProperties().TryGetValue(name, out var property))
{
return property;
}

if (type.GetRuntimeFields().TryGetValue(name, out var field))
{
return field;
}

return null;
return type.GetRuntimeProperties().TryGetValue(name, out var property)
? property
: (MemberInfo)(type.GetRuntimeFields().TryGetValue(name, out var field) ? field : null);
}

/// <summary>
Expand Down
10 changes: 9 additions & 1 deletion src/EFCore/Properties/CoreStrings.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/Properties/CoreStrings.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 @@ -1245,4 +1245,7 @@
<data name="SkipNavigationNonCollection" xml:space="preserve">
<value>The skip navigation '{navigation}' on entity type '{entityType}' is not a collection. Only collection skip navigation properties are currently supported.</value>
</data>
<data name="NonIndexerEntityType" xml:space="preserve">
<value>Cannot add property '{property}' on entity type '{entity}' since there is no indexer on '{entity}' taking a single argument of type '{type}'.</value>
</data>
</root>
Loading

0 comments on commit 9f7ae44

Please sign in to comment.