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

Add nullability check to In-Memory Database #23094

Merged
merged 4 commits into from
Nov 9, 2020
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
14 changes: 11 additions & 3 deletions src/EFCore.InMemory/Properties/InMemoryStrings.Designer.cs

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

5 changes: 4 additions & 1 deletion src/EFCore.InMemory/Properties/InMemoryStrings.resx
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,10 @@
<value>There is no query string because the in-memory provider does not use a string-based query language.</value>
</data>
<data name="NullabilityErrorException" xml:space="preserve">
<value>Required properties '{requiredProperties}' are missing for instance of entity type '{entityType}' with the key value '{keyValue}'</value>
<value>Required properties '{requiredProperties}' are missing for the instance of entity type '{entityType}'. Consider using 'DbContextOptionsBuilder.EnableSensitiveDataLogging' to see the entity key value.</value>
</data>
<data name="NullabilityErrorExceptionSensitive" xml:space="preserve">
<value>Required properties '{requiredProperties}' are missing for the instance of entity type '{entityType}' with the key value '{keyValue}'.</value>
</data>
<data name="UnableToBindMemberToEntityProjection" xml:space="preserve">
<value>Unable to bind '{memberType}' '{member}' to entity projection of '{entityType}'.</value>
Expand Down
28 changes: 18 additions & 10 deletions src/EFCore.InMemory/Storage/Internal/InMemoryTable.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Runtime.InteropServices;
using JetBrains.Annotations;
using Microsoft.EntityFrameworkCore.ChangeTracking;
using Microsoft.EntityFrameworkCore.InMemory.Internal;
Expand Down Expand Up @@ -187,26 +186,26 @@ private static List<ValueComparer> GetKeyComparers(IEnumerable<IProperty> proper
/// </summary>
public virtual void Create(IUpdateEntry entry)
{
var row = entry.EntityType.GetProperties()
.Select(p => SnapshotValue(p, p.GetKeyValueComparer(), entry))
.ToArray();

var properties = entry.EntityType.GetProperties().ToList();
var rows = new object[properties.Count];
var nullabilityErrors = new List<IProperty>();

for (var index = 0; index < properties.Count; index++)
fagnercarvalho marked this conversation as resolved.
Show resolved Hide resolved
{
HasNullabilityError(properties[index], row[index], nullabilityErrors);
var row = SnapshotValue(properties[index], properties[index].GetKeyValueComparer(), entry);
fagnercarvalho marked this conversation as resolved.
Show resolved Hide resolved

rows[index] = row;
HasNullabilityError(properties[index], row, nullabilityErrors);
}

if (nullabilityErrors.Count > 0)
{
ThrowNullabilityErrorException(entry, nullabilityErrors);
}

_rows.Add(CreateKey(entry), row);
_rows.Add(CreateKey(entry), rows);

BumpValueGenerators(row);
BumpValueGenerators(rows);
}

/// <summary>
Expand Down Expand Up @@ -390,11 +389,20 @@ private void ThrowNullabilityErrorException(
Check.NotNull(entry, nameof(entry));
Check.NotNull(nullabilityErrors, nameof(nullabilityErrors));

if (_sensitiveLoggingEnabled)
{
throw new DbUpdateException(
InMemoryStrings.NullabilityErrorExceptionSensitive(
nullabilityErrors.Format(),
entry.EntityType.DisplayName(),
entry.BuildCurrentValuesString(entry.EntityType.FindPrimaryKey().Properties)),
new[] { entry });
}

throw new DbUpdateException(
InMemoryStrings.NullabilityErrorException(
nullabilityErrors.Format(),
entry.EntityType.DisplayName(),
entry.BuildCurrentValuesString(entry.EntityType.FindPrimaryKey().Properties)),
entry.EntityType.DisplayName()),
new[] { entry });
}

Expand Down
3 changes: 3 additions & 0 deletions test/EFCore.InMemory.FunctionalTests/InMemoryFixture.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,9 @@ public class InMemoryFixture
public static IServiceProvider DefaultNullabilityCheckProvider { get; }
= BuildServiceProvider();

public static IServiceProvider DefaultNullabilitySensitiveCheckProvider { get; }
= BuildServiceProvider();

public readonly IServiceProvider ServiceProvider;

public InMemoryFixture()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ public NullabilityCheckInMemoryTest(InMemoryFixture fixture)
public void IsRequired_for_property_throws_while_inserting_null_value()
{
Assert.Equal(
InMemoryStrings.NullabilityErrorException($"{{'{nameof(SomeEntity.Property)}'}}", nameof(SomeEntity), "{Id: 1}"),
InMemoryStrings.NullabilityErrorException($"{{'{nameof(SomeEntity.Property)}'}}", nameof(SomeEntity)),
Assert.Throws<DbUpdateException>(
() =>
{
Expand All @@ -38,11 +38,63 @@ public void IsRequired_for_property_throws_while_inserting_null_value()
}).Message);
}

[ConditionalFact]
public void IsRequired_for_property_throws_while_inserting_null_value_sensitive()
{
Assert.Equal(
InMemoryStrings.NullabilityErrorExceptionSensitive($"{{'{nameof(SomeEntity.Property)}'}}", nameof(SomeEntity), "{Id: 1}"),
Assert.Throws<DbUpdateException>(
() =>
{
var modelBuilder = InMemoryTestHelpers.Instance.CreateConventionBuilder();
modelBuilder.Entity<SomeEntity>(eb => eb.Property(p => p.Property).IsRequired());

var optionsBuilder = new DbContextOptionsBuilder()
.UseModel(modelBuilder.FinalizeModel())
.UseInMemoryDatabase(nameof(NullabilityCheckInMemoryTest))
.UseInternalServiceProvider(InMemoryFixture.DefaultNullabilitySensitiveCheckProvider)
.EnableNullabilityCheck()
.EnableSensitiveDataLogging();

using var context = new DbContext(optionsBuilder.Options);
context.Add(new SomeEntity { Id = 1 });
context.SaveChanges();
}).Message);
}

[ConditionalFact]
public void IsRequired_for_property_throws_while_inserting_null_value_sensitive_with_composite_keys()
{
Assert.Equal(
InMemoryStrings.NullabilityErrorExceptionSensitive($"{{'{nameof(AnotherEntityWithCompositeKeys.Property)}'}}", nameof(AnotherEntityWithCompositeKeys), "{Id: 1, SecondId: 2}"),
Assert.Throws<DbUpdateException>(
() =>
{
var modelBuilder = InMemoryTestHelpers.Instance.CreateConventionBuilder();
modelBuilder.Entity<AnotherEntityWithCompositeKeys>(eb =>
{
eb.Property(p => p.Property).IsRequired();
eb.HasKey(c => new { c.Id, c.SecondId });
});

var optionsBuilder = new DbContextOptionsBuilder()
.UseModel(modelBuilder.FinalizeModel())
.UseInMemoryDatabase(nameof(NullabilityCheckInMemoryTest))
.UseInternalServiceProvider(InMemoryFixture.DefaultNullabilitySensitiveCheckProvider)
.EnableNullabilityCheck()
.EnableSensitiveDataLogging();

using var context = new DbContext(optionsBuilder.Options);
context.Add(new AnotherEntityWithCompositeKeys { Id = 1, SecondId = 2 });
context.SaveChanges();
}).Message);
}

[ConditionalFact]
public void RequiredAttribute_for_property_throws_while_inserting_null_value()
{
Assert.Equal(
InMemoryStrings.NullabilityErrorException($"{{'{nameof(EntityWithRequiredAttribute.RequiredProperty)}'}}", nameof(EntityWithRequiredAttribute), "{Id: 1}"),
InMemoryStrings.NullabilityErrorException($"{{'{nameof(EntityWithRequiredAttribute.RequiredProperty)}'}}", nameof(EntityWithRequiredAttribute)),
Assert.Throws<DbUpdateException>(
() =>
{
Expand All @@ -67,8 +119,7 @@ public void RequiredAttribute_And_IsRequired_for_properties_throws_while_inserti
Assert.Equal(
InMemoryStrings.NullabilityErrorException(
$"{{'{nameof(AnotherEntityWithRequiredAttribute.Property)}', '{nameof(AnotherEntityWithRequiredAttribute.RequiredProperty)}'}}",
nameof(AnotherEntityWithRequiredAttribute),
"{Id: 1}"),
nameof(AnotherEntityWithRequiredAttribute)),
Assert.Throws<DbUpdateException>(
() =>
{
Expand Down Expand Up @@ -168,5 +219,14 @@ private class AnotherEntityWithRequiredAttribute

public string Property { get; set; }
}

private class AnotherEntityWithCompositeKeys
{
public int Id { get; set; }

public int SecondId { get; set; }

public string Property { get; set; }
}
}
}