diff --git a/test/EFCore.Design.Tests/Design/DesignTimeServicesTest.cs b/test/EFCore.Design.Tests/Design/DesignTimeServicesTest.cs index eaa4b8bda3d..13dc4a181fa 100644 --- a/test/EFCore.Design.Tests/Design/DesignTimeServicesTest.cs +++ b/test/EFCore.Design.Tests/Design/DesignTimeServicesTest.cs @@ -247,7 +247,7 @@ public MethodCallCodeFragment GenerateContextOptions() public MethodCallCodeFragment GenerateProviderOptions() => throw new NotImplementedException(); - public MethodCallCodeFragment GenerateUseProvider(string connectionString, MethodCallCodeFragment providerOptions) + public MethodCallCodeFragment GenerateUseProvider(string connectionString, MethodCallCodeFragment? providerOptions) => throw new NotImplementedException(); } @@ -413,8 +413,8 @@ public class MyContext(DbContextOptions options) : DbContext(options) private ServiceProvider CreateDesignServiceProvider( string assemblyCode, - string startupAssemblyCode = null, - DbContext context = null) + string? startupAssemblyCode = null, + DbContext? context = null) { var assembly = Compile(assemblyCode); var startupAssembly = startupAssemblyCode == null diff --git a/test/EFCore.Design.Tests/Design/Internal/CSharpHelperTest.cs b/test/EFCore.Design.Tests/Design/Internal/CSharpHelperTest.cs index b2323024ade..c3c944ddd7b 100644 --- a/test/EFCore.Design.Tests/Design/Internal/CSharpHelperTest.cs +++ b/test/EFCore.Design.Tests/Design/Internal/CSharpHelperTest.cs @@ -9,8 +9,6 @@ namespace Microsoft.EntityFrameworkCore.Design.Internal; -#nullable enable - public class CSharpHelperTest { private static readonly string EOL = Environment.NewLine; diff --git a/test/EFCore.Design.Tests/Design/Internal/DatabaseOperationsTest.cs b/test/EFCore.Design.Tests/Design/Internal/DatabaseOperationsTest.cs index 1f2cbaa02ee..7078d03ff88 100644 --- a/test/EFCore.Design.Tests/Design/Internal/DatabaseOperationsTest.cs +++ b/test/EFCore.Design.Tests/Design/Internal/DatabaseOperationsTest.cs @@ -33,8 +33,8 @@ private void ValidateContextNameInReverseEngineerGenerator(string contextName) "", "", dbContextClassName: contextName, - null, - null, + null!, + null!, "FakeNamespace", contextNamespace: null, useDataAnnotations: false, @@ -56,7 +56,7 @@ public void ScaffoldContext_sets_environment() "", dbContextClassName: nameof(TestContext), schemas: ["Empty"], - null, + null!, null, contextNamespace: null, useDataAnnotations: false, @@ -69,7 +69,7 @@ public void ScaffoldContext_sets_environment() Assert.Equal("Development", Environment.GetEnvironmentVariable("DOTNET_ENVIRONMENT")); } - private static DatabaseOperations CreateOperations(string[] args) + private static DatabaseOperations CreateOperations(string[]? args) { var assembly = MockAssembly.Create(typeof(TestContext)); var operations = new DatabaseOperations( diff --git a/test/EFCore.Design.Tests/Design/Internal/DbContextOperationsTest.cs b/test/EFCore.Design.Tests/Design/Internal/DbContextOperationsTest.cs index 75990d1d066..e2cb56fd1d5 100644 --- a/test/EFCore.Design.Tests/Design/Internal/DbContextOperationsTest.cs +++ b/test/EFCore.Design.Tests/Design/Internal/DbContextOperationsTest.cs @@ -10,7 +10,7 @@ public class DbContextOperationsTest { [Fact] public void CreateContext_gets_service() - => CreateOperations(typeof(TestProgram), includeContext: false).CreateContext(typeof(TestContext).FullName.ToLower()); + => CreateOperations(typeof(TestProgram), includeContext: false).CreateContext(typeof(TestContext).FullName!.ToLower()); [Fact] public void CreateContext_gets_service_without_name() @@ -54,8 +54,8 @@ public void CreateContext_throws_if_ambiguous_context_type_by_case() new TestAppServiceProviderFactory(assembly, reporter)); Assert.Equal( - DesignStrings.MultipleContextsWithName(typeof(TestContext).FullName.ToLower()), - Assert.Throws(() => operations.CreateContext(typeof(TestContext).FullName.ToLower())).Message); + DesignStrings.MultipleContextsWithName(typeof(TestContext).FullName!.ToLower()), + Assert.Throws(() => operations.CreateContext(typeof(TestContext).FullName!.ToLower())).Message); Assert.DoesNotContain(reporter.Messages, m => m.Level == LogLevel.Critical); Assert.DoesNotContain(reporter.Messages, m => m.Level == LogLevel.Error); @@ -289,7 +289,7 @@ public void GetContextInfo_returns_correct_info() [Fact] public void GetContextInfo_does_not_throw_if_DbConnection_cannot_be_created() { - Exception expected = null; + Exception? expected = null; try { new SqlConnection("Cake=None"); @@ -299,6 +299,8 @@ public void GetContextInfo_does_not_throw_if_DbConnection_cannot_be_created() expected = e; } + Assert.NotNull(expected); + var info = CreateOperations(typeof(TestProgramRelationalBad)).GetContextInfo(nameof(TestContext)); Assert.Equal(DesignStrings.BadConnection(expected.Message), info.DatabaseName); diff --git a/test/EFCore.Design.Tests/Design/Internal/LanguageBasedSelectorTests.cs b/test/EFCore.Design.Tests/Design/Internal/LanguageBasedSelectorTests.cs index fb977d18f14..bfd809d36ec 100644 --- a/test/EFCore.Design.Tests/Design/Internal/LanguageBasedSelectorTests.cs +++ b/test/EFCore.Design.Tests/Design/Internal/LanguageBasedSelectorTests.cs @@ -85,8 +85,8 @@ public void Select_uses_last_when_multiple_services() private class TestLanguageBasedSelector(params TestLanguageBasedService[] services) : LanguageBasedSelector(services); - private class TestLanguageBasedService(string language) : ILanguageBasedService + private class TestLanguageBasedService(string? language) : ILanguageBasedService { - public string Language { get; } = language; + public string? Language { get; } = language; } } diff --git a/test/EFCore.Design.Tests/Design/Internal/MigrationsOperationsTest.cs b/test/EFCore.Design.Tests/Design/Internal/MigrationsOperationsTest.cs index f954a5a5921..f9c9049c1ce 100644 --- a/test/EFCore.Design.Tests/Design/Internal/MigrationsOperationsTest.cs +++ b/test/EFCore.Design.Tests/Design/Internal/MigrationsOperationsTest.cs @@ -87,7 +87,7 @@ private class TestContext : DbContext; private class AssemblyTestContext : DbContext { - public static Assembly MigrationsAssembly { get; set; } + public static Assembly MigrationsAssembly { get; set; } = null!; protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) => optionsBuilder.UseSqlServer(o => o.MigrationsAssembly(MigrationsAssembly)); diff --git a/test/EFCore.Design.Tests/Design/Internal/OperationLoggerTest.cs b/test/EFCore.Design.Tests/Design/Internal/OperationLoggerTest.cs index e5a1736426c..21e83d7d9fd 100644 --- a/test/EFCore.Design.Tests/Design/Internal/OperationLoggerTest.cs +++ b/test/EFCore.Design.Tests/Design/Internal/OperationLoggerTest.cs @@ -16,7 +16,7 @@ public void Log_dampens_logLevel_when_CommandExecuted() logger.Log( LogLevel.Information, RelationalEventId.CommandExecuted, - null, + null!, null, (_, __) => "-- Can't stop the SQL"); diff --git a/test/EFCore.Design.Tests/Design/OperationExecutorTest.cs b/test/EFCore.Design.Tests/Design/OperationExecutorTest.cs index 08f8554b088..215769a9fbd 100644 --- a/test/EFCore.Design.Tests/Design/OperationExecutorTest.cs +++ b/test/EFCore.Design.Tests/Design/OperationExecutorTest.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable - using System.Collections; using Microsoft.Data.Sqlite; using Microsoft.EntityFrameworkCore.Internal; diff --git a/test/EFCore.Design.Tests/Design/OperationReportHandlerTest.cs b/test/EFCore.Design.Tests/Design/OperationReportHandlerTest.cs index a22beabaaaf..f1c89a7b20f 100644 --- a/test/EFCore.Design.Tests/Design/OperationReportHandlerTest.cs +++ b/test/EFCore.Design.Tests/Design/OperationReportHandlerTest.cs @@ -22,7 +22,7 @@ public void On_methods_are_noops_when_null() [Fact] public void OnWarning_works() { - string result = null; + string? result = null; var handler = new OperationReportHandler(warningHandler: m => result = m); var message = "Princess Celestia is in danger."; @@ -34,7 +34,7 @@ public void OnWarning_works() [Fact] public void OnInformation_works() { - string result = null; + string? result = null; var handler = new OperationReportHandler(informationHandler: m => result = m); var message = "Princess Celestia is on her way."; @@ -46,7 +46,7 @@ public void OnInformation_works() [Fact] public void OnVerbose_works() { - string result = null; + string? result = null; var handler = new OperationReportHandler(verboseHandler: m => result = m); var message = "Princess Celestia is an alicorn."; diff --git a/test/EFCore.Design.Tests/DesignApiConsistencyTest.cs b/test/EFCore.Design.Tests/DesignApiConsistencyTest.cs index b3f37cbfe92..854dca5c696 100644 --- a/test/EFCore.Design.Tests/DesignApiConsistencyTest.cs +++ b/test/EFCore.Design.Tests/DesignApiConsistencyTest.cs @@ -22,17 +22,17 @@ public class DesignApiConsistencyFixture : ApiConsistencyFixtureBase public override HashSet VirtualMethodExceptions { get; } = [ typeof(CSharpEntityTypeGeneratorBase.ToStringInstanceHelper) - .GetProperty(nameof(CSharpEntityTypeGeneratorBase.ToStringInstanceHelper.FormatProvider)).GetMethod, + .GetProperty(nameof(CSharpEntityTypeGeneratorBase.ToStringInstanceHelper.FormatProvider))!.GetMethod!, typeof(CSharpEntityTypeGeneratorBase.ToStringInstanceHelper) - .GetProperty(nameof(CSharpEntityTypeGeneratorBase.ToStringInstanceHelper.FormatProvider)).SetMethod, + .GetProperty(nameof(CSharpEntityTypeGeneratorBase.ToStringInstanceHelper.FormatProvider))!.SetMethod!, typeof(CSharpEntityTypeGeneratorBase.ToStringInstanceHelper).GetMethod( - nameof(CSharpEntityTypeGeneratorBase.ToStringInstanceHelper.ToStringWithCulture)), + nameof(CSharpEntityTypeGeneratorBase.ToStringInstanceHelper.ToStringWithCulture))!, typeof(CSharpDbContextGeneratorBase.ToStringInstanceHelper) - .GetProperty(nameof(CSharpDbContextGeneratorBase.ToStringInstanceHelper.FormatProvider)).GetMethod, + .GetProperty(nameof(CSharpDbContextGeneratorBase.ToStringInstanceHelper.FormatProvider))!.GetMethod!, typeof(CSharpDbContextGeneratorBase.ToStringInstanceHelper) - .GetProperty(nameof(CSharpDbContextGeneratorBase.ToStringInstanceHelper.FormatProvider)).SetMethod, + .GetProperty(nameof(CSharpDbContextGeneratorBase.ToStringInstanceHelper.FormatProvider))!.SetMethod!, typeof(CSharpDbContextGeneratorBase.ToStringInstanceHelper).GetMethod( - nameof(CSharpDbContextGeneratorBase.ToStringInstanceHelper.ToStringWithCulture)) + nameof(CSharpDbContextGeneratorBase.ToStringInstanceHelper.ToStringWithCulture))! ]; } } diff --git a/test/EFCore.Design.Tests/EFCore.Design.Tests.csproj b/test/EFCore.Design.Tests/EFCore.Design.Tests.csproj index 14c8708d536..3430bcd6ea5 100644 --- a/test/EFCore.Design.Tests/EFCore.Design.Tests.csproj +++ b/test/EFCore.Design.Tests/EFCore.Design.Tests.csproj @@ -5,7 +5,6 @@ true Microsoft.EntityFrameworkCore.Design.Tests Microsoft.EntityFrameworkCore - disable true diff --git a/test/EFCore.Design.Tests/Extensions/MethodCallCodeFragmentExtensionsTest.cs b/test/EFCore.Design.Tests/Extensions/MethodCallCodeFragmentExtensionsTest.cs index 3f2c9e80a39..fd711f71e48 100644 --- a/test/EFCore.Design.Tests/Extensions/MethodCallCodeFragmentExtensionsTest.cs +++ b/test/EFCore.Design.Tests/Extensions/MethodCallCodeFragmentExtensionsTest.cs @@ -16,14 +16,14 @@ public void GetRequiredUsings_works() typeof(TestExtensions1) .GetRuntimeMethod( nameof(TestExtensions1.Extension1), - [typeof(MethodCallCodeFragmentExtensionsTest), typeof(Action)]), + [typeof(MethodCallCodeFragmentExtensionsTest), typeof(Action)])!, new NestedClosureCodeFragment( "x", new MethodCallCodeFragment( typeof(TestExtensions2) .GetRuntimeMethod( nameof(TestExtensions2.Extension2), - [typeof(MethodCallCodeFragmentExtensionsTest), typeof(TestArgument)]), + [typeof(MethodCallCodeFragmentExtensionsTest), typeof(TestArgument)])!, new TestArgument()))); var usings = methodCall.GetRequiredUsings(); diff --git a/test/EFCore.Design.Tests/Migrations/Design/CSharpMigrationOperationGeneratorTest.cs b/test/EFCore.Design.Tests/Migrations/Design/CSharpMigrationOperationGeneratorTest.cs index 1930084ecf6..b046e0a2fe3 100644 --- a/test/EFCore.Design.Tests/Migrations/Design/CSharpMigrationOperationGeneratorTest.cs +++ b/test/EFCore.Design.Tests/Migrations/Design/CSharpMigrationOperationGeneratorTest.cs @@ -2386,7 +2386,7 @@ public void InsertDataOperation_all_args() Columns = ["Id", "Full Name", "Geometry"], Values = new object[,] { - { 0, null, null }, + { 0, null!, null! }, { 1, "Daenerys Targaryen", _point1 }, { 2, "John Snow", _polygon1 }, { 3, "Arya Stark", _lineString1 }, @@ -2475,7 +2475,7 @@ public void InsertDataOperation_required_empty_array() Assert.Single(o.Columns); Assert.Equal(1, o.Values.GetLength(0)); Assert.Equal(1, o.Values.GetLength(1)); - Assert.Equal(new string[0], (string[])o.Values[0, 0]); + Assert.Equal(new string[0], (string[])o.Values[0, 0]!); }); [Fact] @@ -2485,7 +2485,7 @@ public void InsertDataOperation_required_empty_array_composite() { Table = "People", Columns = ["First Name", "Last Name", "Geometry"], - Values = new object[,] { { "John", null, Array.Empty() } } + Values = new object[,] { { "John", null!, Array.Empty() } } }, """ mb.InsertData( @@ -2500,7 +2500,7 @@ public void InsertDataOperation_required_empty_array_composite() Assert.Equal(1, o.Values.GetLength(0)); Assert.Equal(3, o.Values.GetLength(1)); Assert.Null(o.Values[0, 1]); - Assert.Equal(new string[0], (string[])o.Values[0, 2]); + Assert.Equal(new string[0], (string[])o.Values[0, 2]!); }); [Fact] @@ -2642,7 +2642,7 @@ public void DeleteDataOperation_all_args_composite() KeyColumnTypes = ["string", "string"], KeyValues = new object[,] { - { "Hodor", null }, { "Daenerys", "Targaryen" }, { "John", "Snow" }, { "Arya", "Stark" }, { "Harry", "Strickland" } + { "Hodor", null! }, { "Daenerys", "Targaryen" }, { "John", "Snow" }, { "Arya", "Stark" }, { "Harry", "Strickland" } } }, """ @@ -2802,7 +2802,7 @@ public void UpdateDataOperation_all_args_composite() { Table = "People", KeyColumns = ["First Name", "Last Name"], - KeyValues = new object[,] { { "Hodor", null }, { "Daenerys", "Targaryen" } }, + KeyValues = new object[,] { { "Hodor", null! }, { "Daenerys", "Targaryen" } }, Columns = ["House Allegiance"], Values = new object[,] { { "Stark" }, { "Targaryen" } } }, @@ -2842,7 +2842,7 @@ public void UpdateDataOperation_all_args_composite_multi() { Table = "People", KeyColumns = ["First Name", "Last Name"], - KeyValues = new object[,] { { "Hodor", null }, { "Daenerys", "Targaryen" } }, + KeyValues = new object[,] { { "Hodor", null! }, { "Daenerys", "Targaryen" } }, Columns = ["Birthplace", "House Allegiance", "Culture"], Values = new object[,] { { "Winterfell", "Stark", "Northmen" }, { "Dragonstone", "Targaryen", "Valyrian" } } }, @@ -3203,9 +3203,9 @@ public static void Create(MigrationBuilder mb) var assembly = build.BuildInMemory(); var factoryType = assembly.GetType("OperationsFactory"); - var createMethod = factoryType.GetTypeInfo().GetDeclaredMethod("Create"); + var createMethod = factoryType!.GetTypeInfo().GetDeclaredMethod("Create"); var mb = new MigrationBuilder(activeProvider: null); - createMethod.Invoke(null, [mb]); + createMethod!.Invoke(null, [mb]); var result = mb.Operations.Cast().Single(); assert(result); diff --git a/test/EFCore.Design.Tests/Migrations/Design/CSharpMigrationsGeneratorTest.ModelSnapshot.cs b/test/EFCore.Design.Tests/Migrations/Design/CSharpMigrationsGeneratorTest.ModelSnapshot.cs index e3cc80cf98f..03177746721 100644 --- a/test/EFCore.Design.Tests/Migrations/Design/CSharpMigrationsGeneratorTest.ModelSnapshot.cs +++ b/test/EFCore.Design.Tests/Migrations/Design/CSharpMigrationsGeneratorTest.ModelSnapshot.cs @@ -338,7 +338,7 @@ public void Snapshot_default_values_are_round_tripped() foreach (var property in modelBuilder.Model.GetEntityTypes().Single().GetProperties()) { var expected = property.GetDefaultValue(); - var actual = entityType.FindProperty(property.Name).GetDefaultValue(); + var actual = entityType.FindProperty(property.Name)!.GetDefaultValue(); if (actual != null && expected != null) @@ -364,7 +364,7 @@ private class EntityWithEveryPrimitive { public bool Boolean { get; set; } public byte Byte { get; set; } - public byte[] ByteArray { get; set; } + public byte[]? ByteArray { get; set; } public char Char { get; set; } public DateTime DateTime { get; set; } public DateTimeOffset DateTimeOffset { get; set; } @@ -398,7 +398,7 @@ private class EntityWithEveryPrimitive public int PrivateSetter { get; private set; } public sbyte SByte { get; set; } public float Single { get; set; } - public string String { get; set; } + public string? String { get; set; } public TimeSpan TimeSpan { get; set; } public ushort UInt16 { get; set; } public uint UInt32 { get; set; } @@ -416,8 +416,8 @@ public enum Enum1 private class EntityWithManyProperties { public int Id { get; set; } - public string String { get; set; } - public byte[] Bytes { get; set; } + public string? String { get; set; } + public byte[]? Bytes { get; set; } public short Int16 { get; set; } public int Int32 { get; set; } public long Int64 { get; set; } @@ -442,26 +442,26 @@ private class EntityWithManyProperties public EnumU32 EnumU32 { get; set; } public EnumU16 EnumU16 { get; set; } public EnumS8 EnumS8 { get; set; } - public Geometry SpatialBGeometryCollection { get; set; } - public Geometry SpatialBLineString { get; set; } - public Geometry SpatialBMultiLineString { get; set; } - public Geometry SpatialBMultiPoint { get; set; } - public Geometry SpatialBMultiPolygon { get; set; } - public Geometry SpatialBPoint { get; set; } - public Geometry SpatialBPolygon { get; set; } - public GeometryCollection SpatialCGeometryCollection { get; set; } - public LineString SpatialCLineString { get; set; } - public MultiLineString SpatialCMultiLineString { get; set; } - public MultiPoint SpatialCMultiPoint { get; set; } - public MultiPolygon SpatialCMultiPolygon { get; set; } - public Point SpatialCPoint { get; set; } - public Polygon SpatialCPolygon { get; set; } - public int[] Int32Collection { get; set; } - public double[] DoubleCollection { get; set; } - public string[] StringCollection { get; set; } - public DateTime[] DateTimeCollection { get; set; } - public bool[] BoolCollection { get; set; } - public byte[][] BytesCollection { get; set; } + public Geometry? SpatialBGeometryCollection { get; set; } + public Geometry? SpatialBLineString { get; set; } + public Geometry? SpatialBMultiLineString { get; set; } + public Geometry? SpatialBMultiPoint { get; set; } + public Geometry? SpatialBMultiPolygon { get; set; } + public Geometry? SpatialBPoint { get; set; } + public Geometry? SpatialBPolygon { get; set; } + public GeometryCollection? SpatialCGeometryCollection { get; set; } + public LineString? SpatialCLineString { get; set; } + public MultiLineString? SpatialCMultiLineString { get; set; } + public MultiPoint? SpatialCMultiPoint { get; set; } + public MultiPolygon? SpatialCMultiPolygon { get; set; } + public Point? SpatialCPoint { get; set; } + public Polygon? SpatialCPolygon { get; set; } + public int[]? Int32Collection { get; set; } + public double[]? DoubleCollection { get; set; } + public string[]? StringCollection { get; set; } + public DateTime[]? DateTimeCollection { get; set; } + public bool[]? BoolCollection { get; set; } + public byte[][]? BytesCollection { get; set; } } private enum Enum64 : long @@ -561,7 +561,7 @@ public virtual void Unconstrained_foreign_key_is_stored_in_snapshot() """), o => { - var fk = o.FindEntityType(typeof(UnconstrainedFkDependent).FullName)!.GetForeignKeys().Single(); + var fk = o.FindEntityType(typeof(UnconstrainedFkDependent).FullName!)!.GetForeignKeys().Single(); Assert.False(fk.IsConstrained); }); @@ -574,13 +574,13 @@ private class UnconstrainedFkDependent { public int Id { get; set; } public int PrincipalId { get; set; } - public UnconstrainedFkPrincipal Principal { get; set; } + public UnconstrainedFkPrincipal Principal { get; set; } = null!; } private class EntityWithOneProperty { public int Id { get; set; } - public EntityWithTwoProperties EntityWithTwoProperties { get; set; } + public EntityWithTwoProperties? EntityWithTwoProperties { get; set; } } private class EntityWithTwoProperties @@ -591,24 +591,24 @@ private class EntityWithTwoProperties public int AlternateId { get; set; } [NotMapped] - public List List { get; set; } + public List? List { get; set; } [NotMapped] public Coordinates Coordinates { get; set; } - public EntityWithOneProperty EntityWithOneProperty { get; set; } + public EntityWithOneProperty? EntityWithOneProperty { get; set; } [NotMapped] - public EntityWithStringKey EntityWithStringKey { get; set; } + public EntityWithStringKey? EntityWithStringKey { get; set; } } private class EntityWithStringProperty { public int Id { get; set; } - public string Name { get; set; } + public string? Name { get; set; } [NotMapped] - public EntityWithOneProperty EntityWithOneProperty { get; set; } + public EntityWithOneProperty? EntityWithOneProperty { get; set; } } private class EntityWithDecimalProperty @@ -619,15 +619,15 @@ private class EntityWithDecimalProperty private class EntityWithStringKey { - public string Id { get; set; } - public ICollection Properties { get; set; } + public string? Id { get; set; } + public ICollection? Properties { get; set; } } private class EntityWithStringAlternateKey { public int Id { get; set; } - public string AlternateId { get; set; } - public ICollection Properties { get; set; } + public string AlternateId { get; set; } = null!; + public ICollection Properties { get; set; } = null!; } private class EntityWithGenericKey @@ -638,7 +638,7 @@ private class EntityWithGenericKey private class EntityWithGenericProperty { public int Id { get; set; } - public TProperty Property { get; set; } + public TProperty Property { get; set; } = default!; } private class EntityWithThreeProperties @@ -653,30 +653,30 @@ private class EntityWithThreeProperties private class EntityWithIndexAttribute { public int Id { get; set; } - public string FirstName { get; set; } - public string LastName { get; set; } + public string? FirstName { get; set; } + public string? LastName { get; set; } } [Index(nameof(FirstName), nameof(LastName), Name = "NamedIndex")] private class EntityWithNamedIndexAttribute { public int Id { get; set; } - public string FirstName { get; set; } - public string LastName { get; set; } + public string? FirstName { get; set; } + public string? LastName { get; set; } } [Index(nameof(FirstName), nameof(LastName), IsUnique = true)] private class EntityWithUniqueIndexAttribute { public int Id { get; set; } - public string FirstName { get; set; } - public string LastName { get; set; } + public string? FirstName { get; set; } + public string? LastName { get; set; } } public class TestOwner { public int Id { get; set; } - public ICollection OwnedEntities { get; set; } + public ICollection OwnedEntities { get; set; } = null!; } public class TestOwnee @@ -699,22 +699,22 @@ private abstract class AbstractBase private class BaseEntity : AbstractBase { - public string Discriminator { get; set; } + public string? Discriminator { get; set; } } private class DerivedEntity : BaseEntity { - public string Name { get; set; } + public string? Name { get; set; } } private class DuplicateDerivedEntity : BaseEntity { - public string Name { get; set; } + public string? Name { get; set; } } private class AnotherDerivedEntity : BaseEntity { - public string Title { get; set; } + public string? Title { get; set; } } private readonly struct StructDiscriminator @@ -731,19 +731,19 @@ private class BaseEntityWithStructDiscriminator private class DerivedEntityWithStructDiscriminator : BaseEntityWithStructDiscriminator { - public string Name { get; set; } + public string? Name { get; set; } } private class AnotherDerivedEntityWithStructDiscriminator : BaseEntityWithStructDiscriminator { - public string Title { get; set; } + public string? Title { get; set; } } private class BaseType { public int Id { get; set; } - public EntityWithOneProperty Navigation { get; set; } + public EntityWithOneProperty? Navigation { get; set; } } private class DerivedType : BaseType; @@ -774,15 +774,15 @@ private class EntityWithNullableEnumType private class ManyToManyLeft { public int Id { get; set; } - public string Name { get; set; } - public List Rights { get; set; } + public string? Name { get; set; } + public List Rights { get; set; } = null!; } private class ManyToManyRight { public int Id { get; set; } - public string Description { get; set; } - public List Lefts { get; set; } + public string? Description { get; set; } + public List Lefts { get; set; } = null!; } private class CustomValueGenerator : ValueGenerator @@ -797,28 +797,28 @@ public override bool GeneratesTemporaryValues private abstract class Animal { public int Id { get; set; } - public string Name { get; set; } + public string? Name { get; set; } } private abstract class Pet : Animal { - public string Vet { get; set; } + public string? Vet { get; set; } public ICollection Humans { get; } = []; } private class Cat : Pet { - public string EducationLevel { get; set; } + public string? EducationLevel { get; set; } } private class Dog : Pet { - public string FavoriteToy { get; set; } + public string? FavoriteToy { get; set; } } private class Human : Animal { - public Animal FavoriteAnimal { get; set; } + public Animal? FavoriteAnimal { get; set; } public ICollection Pets { get; } = []; } @@ -834,26 +834,26 @@ public class FooExtension { public int Id { get; set; } - public T Bar { get; set; } + public T Bar { get; set; } = null!; } public class Parrot { public int Id { get; set; } - public string Name { get; set; } - public TChild Child { get; set; } + public string? Name { get; set; } + public TChild? Child { get; set; } } public class Parrot { public int Id { get; set; } - public string Name { get; set; } - public Beak Child { get; set; } + public string? Name { get; set; } + public Beak? Child { get; set; } } public class Beak { - public string Name { get; set; } + public string? Name { get; set; } } #region Model @@ -1104,17 +1104,17 @@ public virtual void Entities_are_stored_in_model_snapshot_for_TPT() Assert.Equal(3, model.GetEntityTypes().Count()); var abstractBase = model.FindEntityType( - "Microsoft.EntityFrameworkCore.Migrations.Design.CSharpMigrationsGeneratorTest+AbstractBase"); + "Microsoft.EntityFrameworkCore.Migrations.Design.CSharpMigrationsGeneratorTest+AbstractBase")!; Assert.Equal("AbstractBase", abstractBase.GetTableName()); Assert.Equal("TPT", abstractBase.GetMappingStrategy()); var baseType = model.FindEntityType( - "Microsoft.EntityFrameworkCore.Migrations.Design.CSharpMigrationsGeneratorTest+BaseEntity"); + "Microsoft.EntityFrameworkCore.Migrations.Design.CSharpMigrationsGeneratorTest+BaseEntity")!; Assert.Equal("BaseEntity", baseType.GetTableName()); Assert.Equal("DefaultSchema", baseType.GetSchema()); var derived = model.FindEntityType( - "Microsoft.EntityFrameworkCore.Migrations.Design.CSharpMigrationsGeneratorTest+DerivedEntity"); + "Microsoft.EntityFrameworkCore.Migrations.Design.CSharpMigrationsGeneratorTest+DerivedEntity")!; Assert.Equal("DerivedEntity", derived.GetTableName()); Assert.Equal("foo", derived.GetSchema()); }); @@ -1178,7 +1178,7 @@ public virtual void Entities_are_stored_in_model_snapshot_for_TPT_with_one_exclu Assert.Equal( "DerivedEntity", - o.FindEntityType("Microsoft.EntityFrameworkCore.Migrations.Design.CSharpMigrationsGeneratorTest+DerivedEntity") + o.FindEntityType("Microsoft.EntityFrameworkCore.Migrations.Design.CSharpMigrationsGeneratorTest+DerivedEntity")! .GetTableName()); }); @@ -1312,18 +1312,18 @@ public virtual void Entities_are_stored_in_model_snapshot_for_TPC() Assert.Equal(3, model.GetEntityTypes().Count()); var abstractBase = model.FindEntityType( - "Microsoft.EntityFrameworkCore.Migrations.Design.CSharpMigrationsGeneratorTest+AbstractBase"); + "Microsoft.EntityFrameworkCore.Migrations.Design.CSharpMigrationsGeneratorTest+AbstractBase")!; Assert.Null(abstractBase.GetTableName()); Assert.Null(abstractBase.GetViewName()); Assert.Equal("TPC", abstractBase.GetMappingStrategy()); var baseType = model.FindEntityType( - "Microsoft.EntityFrameworkCore.Migrations.Design.CSharpMigrationsGeneratorTest+BaseEntity"); + "Microsoft.EntityFrameworkCore.Migrations.Design.CSharpMigrationsGeneratorTest+BaseEntity")!; Assert.Equal("BaseEntity", baseType.GetTableName()); Assert.Null(baseType.GetViewName()); var derived = model.FindEntityType( - "Microsoft.EntityFrameworkCore.Migrations.Design.CSharpMigrationsGeneratorTest+DerivedEntity"); + "Microsoft.EntityFrameworkCore.Migrations.Design.CSharpMigrationsGeneratorTest+DerivedEntity")!; Assert.Equal("DerivedEntity", derived.GetTableName()); Assert.Equal("DerivedView", derived.GetViewName()); }); @@ -1474,28 +1474,28 @@ protected override void BuildModel(ModelBuilder modelBuilder) Assert.Equal(6, model.GetEntityTypes().Count()); var animalType = - model.FindEntityType("Microsoft.EntityFrameworkCore.Migrations.Design.CSharpMigrationsGeneratorTest+Animal"); + model.FindEntityType("Microsoft.EntityFrameworkCore.Migrations.Design.CSharpMigrationsGeneratorTest+Animal")!; Assert.Null(animalType.GetTableName()); Assert.Null(animalType.GetViewName()); Assert.Equal("TPC", animalType.GetMappingStrategy()); - var petType = model.FindEntityType("Microsoft.EntityFrameworkCore.Migrations.Design.CSharpMigrationsGeneratorTest+Pet"); + var petType = model.FindEntityType("Microsoft.EntityFrameworkCore.Migrations.Design.CSharpMigrationsGeneratorTest+Pet")!; Assert.Null(petType.GetTableName()); Assert.Null(petType.GetViewName()); - var catType = model.FindEntityType("Microsoft.EntityFrameworkCore.Migrations.Design.CSharpMigrationsGeneratorTest+Cat"); + var catType = model.FindEntityType("Microsoft.EntityFrameworkCore.Migrations.Design.CSharpMigrationsGeneratorTest+Cat")!; Assert.Equal("Cat", catType.GetTableName()); Assert.Null(catType.GetViewName()); - var dogType = model.FindEntityType("Microsoft.EntityFrameworkCore.Migrations.Design.CSharpMigrationsGeneratorTest+Dog"); + var dogType = model.FindEntityType("Microsoft.EntityFrameworkCore.Migrations.Design.CSharpMigrationsGeneratorTest+Dog")!; Assert.Equal("Dog", dogType.GetTableName()); Assert.Null(dogType.GetViewName()); - var humanType = model.FindEntityType("Microsoft.EntityFrameworkCore.Migrations.Design.CSharpMigrationsGeneratorTest+Human"); + var humanType = model.FindEntityType("Microsoft.EntityFrameworkCore.Migrations.Design.CSharpMigrationsGeneratorTest+Human")!; Assert.Equal("Human", humanType.GetTableName()); Assert.Null(humanType.GetViewName()); - var humanPetType = model.FindEntityType("HumanPet"); + var humanPetType = model.FindEntityType("HumanPet")!; Assert.Equal("HumanPet", humanPetType.GetTableName()); Assert.Null(humanPetType.GetViewName()); }); @@ -1588,12 +1588,12 @@ protected override void BuildModel(ModelBuilder modelBuilder) Assert.Equal(5, model.GetAnnotations().Count()); Assert.Equal(2, model.GetEntityTypes().Count()); - var catType = model.FindEntityType("Microsoft.EntityFrameworkCore.Migrations.Design.CSharpMigrationsGeneratorTest+Cat"); + var catType = model.FindEntityType("Microsoft.EntityFrameworkCore.Migrations.Design.CSharpMigrationsGeneratorTest+Cat")!; Assert.Equal("Cats", catType.GetTableName()); Assert.Null(catType.GetViewName()); Assert.Null(catType.FindProperty("Discriminator")); - var dogType = model.FindEntityType("Microsoft.EntityFrameworkCore.Migrations.Design.CSharpMigrationsGeneratorTest+Dog"); + var dogType = model.FindEntityType("Microsoft.EntityFrameworkCore.Migrations.Design.CSharpMigrationsGeneratorTest+Dog")!; Assert.Equal("Dogs", dogType.GetTableName()); Assert.Null(dogType.GetViewName()); }); @@ -1801,37 +1801,37 @@ public virtual void Entity_splitting_is_stored_in_snapshot_with_tables() { Assert.Equal(5, model.GetEntityTypes().Count()); - var orderEntityType = model.FindEntityType(typeof(Order)); + var orderEntityType = model.FindEntityType(typeof(Order))!; Assert.Equal(nameof(Order), orderEntityType.GetTableName()); - var id = orderEntityType.FindProperty("Id"); + var id = orderEntityType.FindProperty("Id")!; Assert.Equal(SqlServerValueGenerationStrategy.IdentityColumn, SqlServerPropertyExtensions.GetValueGenerationStrategy(id)); Assert.Equal(1, id.GetIdentitySeed()); Assert.Equal(1, id.GetIdentityIncrement()); - var overrides = id.FindOverrides(StoreObjectIdentifier.Create(orderEntityType, StoreObjectType.Table).Value)!; + var overrides = id.FindOverrides(StoreObjectIdentifier.Create(orderEntityType, StoreObjectType.Table)!.Value)!; Assert.Equal( SqlServerValueGenerationStrategy.IdentityColumn, SqlServerPropertyExtensions.GetValueGenerationStrategy(overrides)); Assert.Equal(2, overrides.GetIdentitySeed()); Assert.Equal(3, overrides.GetIdentityIncrement()); Assert.Equal("arr", overrides["fii"]); - var billingOwnership = orderEntityType.FindNavigation(nameof(Order.OrderBillingDetails)) + var billingOwnership = orderEntityType.FindNavigation(nameof(Order.OrderBillingDetails))! .ForeignKey; var billingEntityType = billingOwnership.DeclaringEntityType; Assert.Equal("SplitOrder", billingEntityType.GetTableName()); - var billingAddressOwnership = billingEntityType.FindNavigation(nameof(OrderDetails.StreetAddress)) + var billingAddressOwnership = billingEntityType.FindNavigation(nameof(OrderDetails.StreetAddress))! .ForeignKey; var billingAddress = billingAddressOwnership.DeclaringEntityType; Assert.Equal("SplitOrder", billingAddress.GetTableName()); - var shippingOwnership = orderEntityType.FindNavigation(nameof(Order.OrderShippingDetails)) + var shippingOwnership = orderEntityType.FindNavigation(nameof(Order.OrderShippingDetails))! .ForeignKey; var shippingEntityType = shippingOwnership.DeclaringEntityType; Assert.Equal(nameof(Order), shippingEntityType.GetTableName()); - var shippingAddressOwnership = shippingEntityType.FindNavigation(nameof(OrderDetails.StreetAddress)) + var shippingAddressOwnership = shippingEntityType.FindNavigation(nameof(OrderDetails.StreetAddress))! .ForeignKey; var shippingAddress = shippingAddressOwnership.DeclaringEntityType; Assert.Equal("ShippingDetails", shippingAddress.GetTableName()); @@ -1840,16 +1840,16 @@ public virtual void Entity_splitting_is_stored_in_snapshot_with_tables() Assert.Equal(4, relationalModel.Tables.Count()); - var orderTable = relationalModel.FindTable(orderEntityType.GetTableName()!, orderEntityType.GetSchema()); + var orderTable = relationalModel.FindTable(orderEntityType.GetTableName()!, orderEntityType.GetSchema())!; Assert.Equal( [orderEntityType, shippingEntityType], - orderTable.FindColumn("Shadow").PropertyMappings.Select(m => m.TableMapping.TypeBase)); + orderTable.FindColumn("Shadow")!.PropertyMappings.Select(m => m.TableMapping.TypeBase)); var fragment = orderEntityType.GetMappingFragments().Single(); - var splitTable = relationalModel.FindTable(fragment.StoreObject.Name, fragment.StoreObject.Schema); + var splitTable = relationalModel.FindTable(fragment.StoreObject.Name, fragment.StoreObject.Schema)!; Assert.Equal( [orderEntityType, billingEntityType], - splitTable.FindColumn("Shadow").PropertyMappings.Select(m => m.TableMapping.TypeBase)); + splitTable.FindColumn("Shadow")!.PropertyMappings.Select(m => m.TableMapping.TypeBase)); Assert.Equal("bar", fragment["foo"]); var trigger = orderEntityType.GetDeclaredTriggers().Single(); @@ -1858,16 +1858,16 @@ public virtual void Entity_splitting_is_stored_in_snapshot_with_tables() Assert.Equal("rab", trigger["oof"]); var billingFragment = billingEntityType.GetMappingFragments().Single(); - var billingTable = relationalModel.FindTable(billingFragment.StoreObject.Name, billingFragment.StoreObject.Schema); + var billingTable = relationalModel.FindTable(billingFragment.StoreObject.Name, billingFragment.StoreObject.Schema)!; Assert.Equal( [billingEntityType], - billingTable.FindColumn("Shadow").PropertyMappings.Select(m => m.TableMapping.TypeBase)); + billingTable.FindColumn("Shadow")!.PropertyMappings.Select(m => m.TableMapping.TypeBase)); var shippingFragment = shippingEntityType.GetMappingFragments().Single(); - var shippingTable = relationalModel.FindTable(shippingFragment.StoreObject.Name, shippingFragment.StoreObject.Schema); + var shippingTable = relationalModel.FindTable(shippingFragment.StoreObject.Name, shippingFragment.StoreObject.Schema)!; Assert.Equal( [shippingEntityType], - shippingTable.FindColumn("ShippingShadow").PropertyMappings.Select(m => m.TableMapping.TypeBase)); + shippingTable.FindColumn("ShippingShadow")!.PropertyMappings.Select(m => m.TableMapping.TypeBase)); Assert.Equal(["Id", "Shadow"], orderTable.Columns.Select(c => c.Name)); Assert.Equal(["Id", "OrderBillingDetails_StreetAddress_City", "Shadow"], splitTable.Columns.Select(c => c.Name)); @@ -1960,10 +1960,10 @@ public virtual void Entity_splitting_is_stored_in_snapshot_with_views() """), model => { - var entityWithOneProperty = model.FindEntityType(typeof(EntityWithOneProperty)); + var entityWithOneProperty = model.FindEntityType(typeof(EntityWithOneProperty))!; Assert.Equal(nameof(EntityWithOneProperty), entityWithOneProperty.GetViewName()); - var ownership = entityWithOneProperty.FindNavigation(nameof(EntityWithOneProperty.EntityWithTwoProperties)) + var ownership = entityWithOneProperty.FindNavigation(nameof(EntityWithOneProperty.EntityWithTwoProperties))! .ForeignKey; var ownedType = ownership.DeclaringEntityType; Assert.Equal(nameof(EntityWithOneProperty), ownedType.GetViewName()); @@ -1973,10 +1973,10 @@ public virtual void Entity_splitting_is_stored_in_snapshot_with_views() Assert.Empty(relationalModel.Tables); Assert.Equal(2, relationalModel.Views.Count()); - var mainView = relationalModel.FindView(entityWithOneProperty.GetViewName(), "DefaultSchema"); + var mainView = relationalModel.FindView(entityWithOneProperty.GetViewName()!, "DefaultSchema")!; var fragment = entityWithOneProperty.GetMappingFragments().Single(); - var splitView = relationalModel.FindView(fragment.StoreObject.Name, fragment.StoreObject.Schema); + var splitView = relationalModel.FindView(fragment.StoreObject.Name, fragment.StoreObject.Schema)!; Assert.Equal(["Id", "Shadow", "SomeId"], mainView.Columns.Select(c => c.Name)); Assert.Equal(["Id", "Shadow", "SomeOtherId"], splitView.Columns.Select(c => c.Name)); @@ -1988,7 +1988,7 @@ public void Unmapped_entity_types_are_stored_in_the_model_snapshot() builder => { builder.HasDefaultSchema("default"); - builder.Entity().Ignore(e => e.EntityWithTwoProperties).ToTable((string)null) + builder.Entity().Ignore(e => e.EntityWithTwoProperties).ToTable((string)null!) .UpdateUsingStoredProcedure("Update", "sproc", p => p.HasParameter(e => e.Id)); }, AddBoilerPlate( @@ -2017,7 +2017,7 @@ public void Unmapped_entity_types_are_stored_in_the_model_snapshot() private class TestKeylessType { - public string Something { get; set; } + public string? Something { get; set; } } private static IQueryable GetCountByYear(int id) @@ -2031,9 +2031,9 @@ public void TVF_types_are_stored_in_the_model_snapshot() builder.HasDbFunction( typeof(CSharpMigrationsGeneratorTest).GetMethod( nameof(GetCountByYear), - BindingFlags.NonPublic | BindingFlags.Static)); + BindingFlags.NonPublic | BindingFlags.Static)!); - builder.Entity().HasNoKey().ToTable((string)null); + builder.Entity().HasNoKey().ToTable((string)null!); }, AddBoilerPlate( GetHeading() @@ -2263,7 +2263,7 @@ public virtual void CheckConstraint_is_only_stored_in_snapshot_once_for_TPH() """), o => { - var constraint = o.FindEntityType(typeof(DerivedEntity)).GetDeclaredCheckConstraints().Single(); + var constraint = o.FindEntityType(typeof(DerivedEntity))!.GetDeclaredCheckConstraints().Single(); Assert.Equal("CK_BaseEntity_AlternateId", constraint.Name); }); @@ -2473,7 +2473,7 @@ public virtual void Model_use_identity_columns_custom_seed_increment() Assert.Equal(long.MaxValue, o.GetIdentitySeed()); Assert.Equal(5, o.GetIdentityIncrement()); - var property = o.FindEntityType("Building").FindProperty("Id"); + var property = o.FindEntityType("Building")!.FindProperty("Id")!; Assert.Equal( SqlServerValueGenerationStrategy.IdentityColumn, SqlServerPropertyExtensions.GetValueGenerationStrategy(property)); Assert.Equal(long.MaxValue, property.GetIdentitySeed()); @@ -2672,12 +2672,12 @@ public virtual void Discriminator_annotations_are_stored_in_snapshot() """), o => { - Assert.Equal("Discriminator", o.FindEntityType(typeof(BaseEntity))[CoreAnnotationNames.DiscriminatorProperty]); - Assert.Equal("BaseEntity", o.FindEntityType(typeof(BaseEntity))[CoreAnnotationNames.DiscriminatorValue]); + Assert.Equal("Discriminator", o.FindEntityType(typeof(BaseEntity))![CoreAnnotationNames.DiscriminatorProperty]); + Assert.Equal("BaseEntity", o.FindEntityType(typeof(BaseEntity))![CoreAnnotationNames.DiscriminatorValue]); Assert.Equal( "AnotherDerivedEntity", - o.FindEntityType(typeof(AnotherDerivedEntity))[CoreAnnotationNames.DiscriminatorValue]); - Assert.Equal("DerivedEntity", o.FindEntityType(typeof(DerivedEntity))[CoreAnnotationNames.DiscriminatorValue]); + o.FindEntityType(typeof(AnotherDerivedEntity))![CoreAnnotationNames.DiscriminatorValue]); + Assert.Equal("DerivedEntity", o.FindEntityType(typeof(DerivedEntity))![CoreAnnotationNames.DiscriminatorValue]); }); [Fact] @@ -2747,7 +2747,7 @@ public virtual void Converted_discriminator_annotations_are_stored_in_snapshot() """), o => { - var baseEntityType = o.FindEntityType(typeof(BaseEntityWithStructDiscriminator)); + var baseEntityType = o.FindEntityType(typeof(BaseEntityWithStructDiscriminator))!; Assert.Equal( "Discriminator", baseEntityType[CoreAnnotationNames.DiscriminatorProperty]); @@ -2756,17 +2756,17 @@ public virtual void Converted_discriminator_annotations_are_stored_in_snapshot() "Base", baseEntityType[CoreAnnotationNames.DiscriminatorValue]); - var discriminatorProperty = baseEntityType.FindDiscriminatorProperty(); + var discriminatorProperty = baseEntityType.FindDiscriminatorProperty()!; Assert.Equal(typeof(string), discriminatorProperty.ClrType); Assert.Equal("Discriminator", discriminatorProperty.Name); Assert.Equal( "Another", - o.FindEntityType(typeof(AnotherDerivedEntityWithStructDiscriminator))[CoreAnnotationNames.DiscriminatorValue]); + o.FindEntityType(typeof(AnotherDerivedEntityWithStructDiscriminator))![CoreAnnotationNames.DiscriminatorValue]); Assert.Equal( "Derived", - o.FindEntityType(typeof(DerivedEntityWithStructDiscriminator))[CoreAnnotationNames.DiscriminatorValue]); + o.FindEntityType(typeof(DerivedEntityWithStructDiscriminator))![CoreAnnotationNames.DiscriminatorValue]); }); [Fact] @@ -2832,9 +2832,9 @@ public virtual void Primary_key_is_stored_in_snapshot() """), o => { - Assert.Equal(2, o.GetEntityTypes().First().FindPrimaryKey().Properties.Count); + Assert.Equal(2, o.GetEntityTypes().First().FindPrimaryKey()!.Properties.Count); Assert.Collection( - o.GetEntityTypes().First().FindPrimaryKey().Properties, + o.GetEntityTypes().First().FindPrimaryKey()!.Properties, t => Assert.Equal("Id", t.Name), t => Assert.Equal("AlternateId", t.Name) ); @@ -3032,10 +3032,10 @@ public virtual void Foreign_keys_are_stored_in_snapshot() """), o => { - var foreignKey = o.FindEntityType(typeof(EntityWithTwoProperties)).GetForeignKeys().Single(); + var foreignKey = o.FindEntityType(typeof(EntityWithTwoProperties))!.GetForeignKeys().Single(); Assert.Equal("AlternateId", foreignKey.Properties[0].Name); - Assert.Equal("EntityWithTwoProperties", foreignKey.PrincipalToDependent.Name); - Assert.Equal("EntityWithOneProperty", foreignKey.DependentToPrincipal.Name); + Assert.Equal("EntityWithTwoProperties", foreignKey.PrincipalToDependent!.Name); + Assert.Equal("EntityWithOneProperty", foreignKey.DependentToPrincipal!.Name); }); [Fact] @@ -3120,7 +3120,7 @@ public virtual void Many_to_many_join_table_stored_in_snapshot() """), model => { - var joinEntity = model.FindEntityType("ManyToManyLeftManyToManyRight"); + var joinEntity = model.FindEntityType("ManyToManyLeftManyToManyRight")!; Assert.Equal(typeof(Dictionary), joinEntity.ClrType); Assert.Collection( joinEntity.GetDeclaredProperties(), @@ -3135,7 +3135,7 @@ public virtual void Many_to_many_join_table_stored_in_snapshot() Assert.False(p.IsShadowProperty()); }); Assert.Collection( - joinEntity.FindDeclaredPrimaryKey().Properties, + joinEntity.FindDeclaredPrimaryKey()!.Properties, p => Assert.Equal("LeftsId", p.Name), p => Assert.Equal("RightsId", p.Name)); Assert.Collection( @@ -3247,7 +3247,7 @@ public virtual void Can_override_table_name_for_many_to_many_join_table_stored_i """), model => { - var joinEntity = model.FindEntityType("ManyToManyLeftManyToManyRight"); + var joinEntity = model.FindEntityType("ManyToManyLeftManyToManyRight")!; Assert.Equal(typeof(Dictionary), joinEntity.ClrType); Assert.Equal("MyJoinTable", joinEntity.GetTableName()); Assert.Collection( @@ -3265,7 +3265,7 @@ public virtual void Can_override_table_name_for_many_to_many_join_table_stored_i Assert.True(p.IsIndexerProperty()); }); Assert.Collection( - joinEntity.FindDeclaredPrimaryKey().Properties, + joinEntity.FindDeclaredPrimaryKey()!.Properties, p => Assert.Equal("LeftsId", p.Name), p => Assert.Equal("RightsId", p.Name)); Assert.Collection( @@ -3299,7 +3299,7 @@ public virtual void Can_override_table_name_for_many_to_many_join_table_stored_i [Fact] public virtual void TableName_preserved_when_generic() { - IReadOnlyModel originalModel = null; + IReadOnlyModel originalModel = null!; Test( builder => @@ -3324,8 +3324,8 @@ public virtual void TableName_preserved_when_generic() """, usingSystem: true), model => { - var originalEntity = originalModel.FindEntityType(typeof(EntityWithGenericKey)); - var entity = model.FindEntityType(originalEntity.Name); + var originalEntity = originalModel.FindEntityType(typeof(EntityWithGenericKey))!; + var entity = model.FindEntityType(originalEntity.Name)!; Assert.NotNull(entity); Assert.Equal(originalEntity.GetTableName(), entity.GetTableName()); @@ -3404,15 +3404,15 @@ public virtual void Shared_columns_are_stored_in_the_snapshot() """, usingSystem: false), model => { - var entityType = model.FindEntityType(typeof(EntityWithOneProperty)); + var entityType = model.FindEntityType(typeof(EntityWithOneProperty))!; - Assert.Equal(ValueGenerated.OnUpdateSometimes, entityType.FindProperty("AlternateId").ValueGenerated); + Assert.Equal(ValueGenerated.OnUpdateSometimes, entityType.FindProperty("AlternateId")!.ValueGenerated); }); [Fact] public virtual void PrimaryKey_name_preserved_when_generic() { - IReadOnlyModel originalModel = null; + IReadOnlyModel originalModel = null!; Test( builder => @@ -3437,12 +3437,12 @@ public virtual void PrimaryKey_name_preserved_when_generic() """, usingSystem: true), model => { - var originalEntity = originalModel.FindEntityType(typeof(EntityWithGenericKey)); - var entity = model.FindEntityType(originalEntity.Name); + var originalEntity = originalModel.FindEntityType(typeof(EntityWithGenericKey))!; + var entity = model.FindEntityType(originalEntity.Name)!; Assert.NotNull(entity); - var originalPrimaryKey = originalEntity.FindPrimaryKey(); - var primaryKey = entity.FindPrimaryKey(); + var originalPrimaryKey = originalEntity.FindPrimaryKey()!; + var primaryKey = entity.FindPrimaryKey()!; Assert.Equal(originalPrimaryKey.GetName(), primaryKey.GetName()); }); @@ -3451,7 +3451,7 @@ public virtual void PrimaryKey_name_preserved_when_generic() [Fact] public virtual void AlternateKey_name_preserved_when_generic() { - IReadOnlyModel originalModel = null; + IReadOnlyModel originalModel = null!; Test( builder => @@ -3483,12 +3483,12 @@ public virtual void AlternateKey_name_preserved_when_generic() """, usingSystem: true), model => { - var originalEntity = originalModel.FindEntityType(typeof(EntityWithGenericProperty)); - var entity = model.FindEntityType(originalEntity.Name); + var originalEntity = originalModel.FindEntityType(typeof(EntityWithGenericProperty))!; + var entity = model.FindEntityType(originalEntity.Name)!; Assert.NotNull(entity); - var originalAlternateKey = originalEntity.FindKey(originalEntity.FindProperty("Property")); - var alternateKey = entity.FindKey(entity.FindProperty("Property")); + var originalAlternateKey = originalEntity.FindKey(originalEntity.FindProperty("Property")!)!; + var alternateKey = entity.FindKey(entity.FindProperty("Property")!)!; Assert.Equal(originalAlternateKey.GetName(), alternateKey.GetName()); }); @@ -3519,7 +3519,7 @@ public virtual void Discriminator_of_enum() b.HasDiscriminator("Day"); }); """), - model => Assert.Equal(typeof(long), model.GetEntityTypes().First().FindDiscriminatorProperty().ClrType)); + model => Assert.Equal(typeof(long), model.GetEntityTypes().First().FindDiscriminatorProperty()!.ClrType)); [Fact] public virtual void Discriminator_of_enum_to_string() @@ -3553,7 +3553,7 @@ public virtual void Discriminator_of_enum_to_string() """), model => { - var discriminatorProperty = model.GetEntityTypes().First().FindDiscriminatorProperty(); + var discriminatorProperty = model.GetEntityTypes().First().FindDiscriminatorProperty()!; Assert.Equal(typeof(string), discriminatorProperty.ClrType); Assert.False(discriminatorProperty.IsNullable); }); @@ -3602,7 +3602,7 @@ public virtual void Discriminator_with_non_string_default_name_is_stored_in_snap """), model => { - var discriminatorProperty = model.FindEntityType(typeof(BaseType))!.FindDiscriminatorProperty(); + var discriminatorProperty = model.FindEntityType(typeof(BaseType))!.FindDiscriminatorProperty()!; Assert.Equal(typeof(int), discriminatorProperty.ClrType); Assert.Equal("Discriminator", discriminatorProperty.Name); }); @@ -3659,7 +3659,7 @@ public virtual void Temporal_table_information_is_stored_in_snapshot() o => { var temporalEntity = o.FindEntityType( - "Microsoft.EntityFrameworkCore.Migrations.Design.CSharpMigrationsGeneratorTest+EntityWithStringProperty"); + "Microsoft.EntityFrameworkCore.Migrations.Design.CSharpMigrationsGeneratorTest+EntityWithStringProperty")!; var annotations = temporalEntity.GetAnnotations().ToList(); Assert.Equal(7, annotations.Count); @@ -3721,7 +3721,7 @@ public virtual void Temporal_table_information_is_stored_in_snapshot_minimal_set o => { var temporalEntity = o.FindEntityType( - "Microsoft.EntityFrameworkCore.Migrations.Design.CSharpMigrationsGeneratorTest+EntityWithStringProperty"); + "Microsoft.EntityFrameworkCore.Migrations.Design.CSharpMigrationsGeneratorTest+EntityWithStringProperty")!; var annotations = temporalEntity.GetAnnotations().ToList(); Assert.Equal(7, annotations.Count); @@ -3788,7 +3788,7 @@ public virtual void Temporal_table_with_visible_period_columns_is_stored_in_snap o => { var temporalEntity = o.FindEntityType( - "Microsoft.EntityFrameworkCore.Migrations.Design.CSharpMigrationsGeneratorTest+EntityWithStringProperty"); + "Microsoft.EntityFrameworkCore.Migrations.Design.CSharpMigrationsGeneratorTest+EntityWithStringProperty")!; Assert.True(temporalEntity.IsTemporal()); Assert.False(temporalEntity.GetProperty("Start").IsHidden()); @@ -3962,18 +3962,18 @@ public virtual void Owned_types_are_stored_in_snapshot() """), o => { - var entityWithOneProperty = o.FindEntityType(typeof(EntityWithOneProperty)); + var entityWithOneProperty = o.FindEntityType(typeof(EntityWithOneProperty))!; Assert.Equal("PK_Custom", entityWithOneProperty.GetKeys().Single().GetName()); Assert.Equal([1], entityWithOneProperty.GetSeedData().Single().Values); - var ownership1 = entityWithOneProperty.FindNavigation(nameof(EntityWithOneProperty.EntityWithTwoProperties)) + var ownership1 = entityWithOneProperty.FindNavigation(nameof(EntityWithOneProperty.EntityWithTwoProperties))! .ForeignKey; Assert.Equal(nameof(EntityWithTwoProperties.AlternateId), ownership1.Properties[0].Name); - Assert.Equal(nameof(EntityWithTwoProperties.EntityWithOneProperty), ownership1.DependentToPrincipal.Name); + Assert.Equal(nameof(EntityWithTwoProperties.EntityWithOneProperty), ownership1.DependentToPrincipal!.Name); Assert.True(ownership1.IsRequired); Assert.Equal("FK_Custom", ownership1.GetConstraintName()); var ownedType1 = ownership1.DeclaringEntityType; - Assert.Equal(nameof(EntityWithTwoProperties.AlternateId), ownedType1.FindPrimaryKey().Properties[0].Name); + Assert.Equal(nameof(EntityWithTwoProperties.AlternateId), ownedType1.FindPrimaryKey()!.Properties[0].Name); Assert.Equal("PK_Custom", ownedType1.GetKeys().Single().GetName()); Assert.Equal(2, ownedType1.GetIndexes().Count()); var owned1index1 = ownedType1.GetIndexes().First(); @@ -3990,18 +3990,18 @@ public virtual void Owned_types_are_stored_in_snapshot() Assert.Equal(nameof(EntityWithOneProperty), ownedType1.GetTableName()); Assert.False(ownedType1.IsTableExcludedFromMigrations()); - var entityWithStringKey = o.FindEntityType(typeof(EntityWithStringKey)); + var entityWithStringKey = o.FindEntityType(typeof(EntityWithStringKey))!; Assert.Same( entityWithStringKey, - ownedType1.FindNavigation(nameof(EntityWithTwoProperties.EntityWithStringKey)).TargetEntityType); + ownedType1.FindNavigation(nameof(EntityWithTwoProperties.EntityWithStringKey))!.TargetEntityType); Assert.Equal(nameof(EntityWithStringKey), entityWithStringKey.GetTableName()); - var ownership2 = entityWithStringKey.FindNavigation(nameof(EntityWithStringKey.Properties)).ForeignKey; + var ownership2 = entityWithStringKey.FindNavigation(nameof(EntityWithStringKey.Properties))!.ForeignKey; Assert.Equal("EntityWithStringKeyId", ownership2.Properties[0].Name); Assert.Null(ownership2.DependentToPrincipal); Assert.True(ownership2.IsRequired); var ownedType2 = ownership2.DeclaringEntityType; - Assert.Equal(nameof(EntityWithStringProperty.Id), ownedType2.FindPrimaryKey().Properties[0].Name); + Assert.Equal(nameof(EntityWithStringProperty.Id), ownedType2.FindPrimaryKey()!.Properties[0].Name); Assert.Single(ownedType2.GetKeys()); Assert.Equal(2, ownedType2.GetIndexes().Count()); var owned2index1 = ownedType2.GetIndexes().First(); @@ -4196,18 +4196,18 @@ public virtual void Owned_types_are_stored_in_snapshot_when_excluded() """), o => { - var entityWithOneProperty = o.FindEntityType(typeof(EntityWithOneProperty)); + var entityWithOneProperty = o.FindEntityType(typeof(EntityWithOneProperty))!; Assert.Equal("PK_Custom", entityWithOneProperty.GetKeys().Single().GetName()); Assert.Equal([1], entityWithOneProperty.GetSeedData().Single().Values); - var ownership1 = entityWithOneProperty.FindNavigation(nameof(EntityWithOneProperty.EntityWithTwoProperties)) + var ownership1 = entityWithOneProperty.FindNavigation(nameof(EntityWithOneProperty.EntityWithTwoProperties))! .ForeignKey; Assert.Equal(nameof(EntityWithTwoProperties.AlternateId), ownership1.Properties[0].Name); - Assert.Equal(nameof(EntityWithTwoProperties.EntityWithOneProperty), ownership1.DependentToPrincipal.Name); + Assert.Equal(nameof(EntityWithTwoProperties.EntityWithOneProperty), ownership1.DependentToPrincipal!.Name); Assert.True(ownership1.IsRequired); Assert.Equal("FK_Custom", ownership1.GetConstraintName()); var ownedType1 = ownership1.DeclaringEntityType; - Assert.Equal(nameof(EntityWithTwoProperties.AlternateId), ownedType1.FindPrimaryKey().Properties[0].Name); + Assert.Equal(nameof(EntityWithTwoProperties.AlternateId), ownedType1.FindPrimaryKey()!.Properties[0].Name); Assert.Equal("PK_Custom", ownedType1.GetKeys().Single().GetName()); Assert.Equal(2, ownedType1.GetIndexes().Count()); var owned1index1 = ownedType1.GetIndexes().First(); @@ -4222,19 +4222,19 @@ public virtual void Owned_types_are_stored_in_snapshot_when_excluded() Assert.Equal(nameof(EntityWithOneProperty), ownedType1.GetTableName()); Assert.True(ownedType1.IsTableExcludedFromMigrations()); - var entityWithStringKey = o.FindEntityType(typeof(EntityWithStringKey)); + var entityWithStringKey = o.FindEntityType(typeof(EntityWithStringKey))!; Assert.Same( entityWithStringKey, - ownedType1.FindNavigation(nameof(EntityWithTwoProperties.EntityWithStringKey)).TargetEntityType); + ownedType1.FindNavigation(nameof(EntityWithTwoProperties.EntityWithStringKey))!.TargetEntityType); Assert.Equal(nameof(EntityWithStringKey), entityWithStringKey.GetTableName()); Assert.True(entityWithStringKey.IsTableExcludedFromMigrations()); - var ownership2 = entityWithStringKey.FindNavigation(nameof(EntityWithStringKey.Properties)).ForeignKey; + var ownership2 = entityWithStringKey.FindNavigation(nameof(EntityWithStringKey.Properties))!.ForeignKey; Assert.Equal("EntityWithStringKeyId", ownership2.Properties[0].Name); Assert.Null(ownership2.DependentToPrincipal); Assert.True(ownership2.IsRequired); var ownedType2 = ownership2.DeclaringEntityType; - Assert.Equal(nameof(EntityWithStringProperty.Id), ownedType2.FindPrimaryKey().Properties[0].Name); + Assert.Equal(nameof(EntityWithStringProperty.Id), ownedType2.FindPrimaryKey()!.Properties[0].Name); Assert.Single(ownedType2.GetKeys()); Assert.Equal(2, ownedType2.GetIndexes().Count()); var owned2index1 = ownedType2.GetIndexes().First(); @@ -4382,27 +4382,27 @@ public virtual void Shared_owned_types_are_stored_in_snapshot() { Assert.Equal(7, o.GetEntityTypes().Count()); - var order = (IRuntimeEntityType)o.FindEntityType(typeof(Order).FullName); + var order = (IRuntimeEntityType)o.FindEntityType(typeof(Order).FullName!)!; Assert.Equal(1, order.PropertyCount); - var orderInfo = (IRuntimeEntityType)order.FindNavigation(nameof(Order.OrderInfo)).TargetEntityType; + var orderInfo = (IRuntimeEntityType)order.FindNavigation(nameof(Order.OrderInfo))!.TargetEntityType; Assert.Equal(1, orderInfo.PropertyCount); - var orderInfoAddress = (IRuntimeEntityType)orderInfo.FindNavigation(nameof(OrderInfo.StreetAddress)).TargetEntityType; + var orderInfoAddress = (IRuntimeEntityType)orderInfo.FindNavigation(nameof(OrderInfo.StreetAddress))!.TargetEntityType; Assert.Equal(2, orderInfoAddress.PropertyCount); - var orderBillingDetails = (IRuntimeEntityType)order.FindNavigation(nameof(Order.OrderBillingDetails)).TargetEntityType; + var orderBillingDetails = (IRuntimeEntityType)order.FindNavigation(nameof(Order.OrderBillingDetails))!.TargetEntityType; Assert.Equal(1, orderBillingDetails.PropertyCount); var orderBillingDetailsAddress = - (IRuntimeEntityType)orderBillingDetails.FindNavigation(nameof(OrderDetails.StreetAddress)).TargetEntityType; + (IRuntimeEntityType)orderBillingDetails.FindNavigation(nameof(OrderDetails.StreetAddress))!.TargetEntityType; Assert.Equal(2, orderBillingDetailsAddress.PropertyCount); - var orderShippingDetails = (IRuntimeEntityType)order.FindNavigation(nameof(Order.OrderShippingDetails)).TargetEntityType; + var orderShippingDetails = (IRuntimeEntityType)order.FindNavigation(nameof(Order.OrderShippingDetails))!.TargetEntityType; Assert.Equal(1, orderShippingDetails.PropertyCount); var orderShippingDetailsAddress = - (IRuntimeEntityType)orderShippingDetails.FindNavigation(nameof(OrderDetails.StreetAddress)).TargetEntityType; + (IRuntimeEntityType)orderShippingDetails.FindNavigation(nameof(OrderDetails.StreetAddress))!.TargetEntityType; Assert.Equal(2, orderShippingDetailsAddress.PropertyCount); }); @@ -4483,9 +4483,9 @@ protected override void BuildModel(ModelBuilder modelBuilder) { Assert.Equal(2, model.GetEntityTypes().Count()); var testOwner = model.FindEntityType( - "Microsoft.EntityFrameworkCore.Migrations.Design.CSharpMigrationsGeneratorTest+TestOwner"); + "Microsoft.EntityFrameworkCore.Migrations.Design.CSharpMigrationsGeneratorTest+TestOwner")!; var testOwnee = model.FindEntityType( - "Microsoft.EntityFrameworkCore.Migrations.Design.CSharpMigrationsGeneratorTest+TestOwnee", "OwnedEntities", testOwner); + "Microsoft.EntityFrameworkCore.Migrations.Design.CSharpMigrationsGeneratorTest+TestOwnee", "OwnedEntities", testOwner)!; Assert.Equal("OwnedView", testOwnee.GetViewName()); }); @@ -4571,9 +4571,9 @@ protected override void BuildModel(ModelBuilder modelBuilder) { Assert.Equal(2, model.GetEntityTypes().Count()); var testOwner = model.FindEntityType( - "Microsoft.EntityFrameworkCore.Migrations.Design.CSharpMigrationsGeneratorTest+TestOwner"); + "Microsoft.EntityFrameworkCore.Migrations.Design.CSharpMigrationsGeneratorTest+TestOwner")!; var testOwnee = model.FindEntityType( - "Microsoft.EntityFrameworkCore.Migrations.Design.CSharpMigrationsGeneratorTest+TestOwnee", "OwnedEntities", testOwner); + "Microsoft.EntityFrameworkCore.Migrations.Design.CSharpMigrationsGeneratorTest+TestOwnee", "OwnedEntities", testOwner)!; Assert.NotNull(testOwnee.FindCheckConstraint("CK_TestOwnee_TestEnum_Enum_Constraint")); }); @@ -4681,18 +4681,18 @@ public virtual void Owned_types_mapped_to_json_are_stored_in_snapshot() """, usingSystem: false), o => { - var entityWithOneProperty = o.FindEntityType(typeof(EntityWithOneProperty)); + var entityWithOneProperty = o.FindEntityType(typeof(EntityWithOneProperty))!; Assert.Equal("PK_Custom", entityWithOneProperty.GetKeys().Single().GetName()); - var ownership1 = entityWithOneProperty.FindNavigation(nameof(EntityWithOneProperty.EntityWithTwoProperties)) + var ownership1 = entityWithOneProperty.FindNavigation(nameof(EntityWithOneProperty.EntityWithTwoProperties))! .ForeignKey; Assert.Equal("EntityWithOnePropertyId", ownership1.Properties[0].Name); - Assert.Equal(nameof(EntityWithTwoProperties.EntityWithOneProperty), ownership1.DependentToPrincipal.Name); + Assert.Equal(nameof(EntityWithTwoProperties.EntityWithOneProperty), ownership1.DependentToPrincipal!.Name); Assert.True(ownership1.IsRequired); Assert.Equal("FK_EntityWithOneProperty_EntityWithOneProperty_EntityWithOnePropertyId", ownership1.GetConstraintName()); var ownedType1 = ownership1.DeclaringEntityType; - Assert.Equal("EntityWithOnePropertyId", ownedType1.FindPrimaryKey().Properties[0].Name); + Assert.Equal("EntityWithOnePropertyId", ownedType1.FindPrimaryKey()!.Properties[0].Name); var ownedProperties1 = ownedType1.GetProperties().ToList(); Assert.Equal("EntityWithOnePropertyId", ownedProperties1[0].Name); @@ -4703,29 +4703,29 @@ public virtual void Owned_types_mapped_to_json_are_stored_in_snapshot() Assert.Equal("EntityWithTwoProperties", ownedType1.GetContainerColumnName()); Assert.Equal("nvarchar(max)", ownedType1.GetContainerColumnType()); - var ownership2 = ownedType1.FindNavigation(nameof(EntityWithStringKey)).ForeignKey; + var ownership2 = ownedType1.FindNavigation(nameof(EntityWithStringKey))!.ForeignKey; Assert.Equal("EntityWithTwoPropertiesEntityWithOnePropertyId", ownership2.Properties[0].Name); - Assert.Equal(nameof(EntityWithTwoProperties.EntityWithStringKey), ownership2.PrincipalToDependent.Name); + Assert.Equal(nameof(EntityWithTwoProperties.EntityWithStringKey), ownership2.PrincipalToDependent!.Name); Assert.True(ownership2.IsRequired); var ownedType2 = ownership2.DeclaringEntityType; Assert.Equal(nameof(EntityWithStringKey), ownedType2.DisplayName()); - Assert.Equal("EntityWithTwoPropertiesEntityWithOnePropertyId", ownedType2.FindPrimaryKey().Properties[0].Name); + Assert.Equal("EntityWithTwoPropertiesEntityWithOnePropertyId", ownedType2.FindPrimaryKey()!.Properties[0].Name); var ownedProperties2 = ownedType2.GetProperties().ToList(); Assert.Equal("EntityWithTwoPropertiesEntityWithOnePropertyId", ownedProperties2[0].Name); - var navigation3 = ownedType2.FindNavigation(nameof(EntityWithStringKey.Properties)); + var navigation3 = ownedType2.FindNavigation(nameof(EntityWithStringKey.Properties))!; Assert.Equal("JsonProps", navigation3.TargetEntityType.GetJsonPropertyName()); var ownership3 = navigation3.ForeignKey; Assert.Equal("EntityWithStringKeyEntityWithTwoPropertiesEntityWithOnePropertyId", ownership3.Properties[0].Name); - Assert.Equal(nameof(EntityWithStringKey.Properties), ownership3.PrincipalToDependent.Name); + Assert.Equal(nameof(EntityWithStringKey.Properties), ownership3.PrincipalToDependent!.Name); Assert.True(ownership3.IsRequired); Assert.False(ownership3.IsUnique); var ownedType3 = ownership3.DeclaringEntityType; Assert.Equal(nameof(EntityWithStringProperty), ownedType3.DisplayName()); - var pkProperties3 = ownedType3.FindPrimaryKey().Properties; + var pkProperties3 = ownedType3.FindPrimaryKey()!.Properties; Assert.Equal("EntityWithStringKeyEntityWithTwoPropertiesEntityWithOnePropertyId", pkProperties3[0].Name); Assert.Equal("__synthesizedOrdinal", pkProperties3[1].Name); @@ -4799,10 +4799,10 @@ public virtual void Owned_types_mapped_to_json_with_explicit_column_type_are_sto """, usingSystem: false), o => { - var entityWithOneProperty = o.FindEntityType(typeof(EntityWithOneProperty)); + var entityWithOneProperty = o.FindEntityType(typeof(EntityWithOneProperty))!; Assert.Equal("PK_Custom", entityWithOneProperty.GetKeys().Single().GetName()); - var ownership1 = entityWithOneProperty.FindNavigation(nameof(EntityWithOneProperty.EntityWithTwoProperties)) + var ownership1 = entityWithOneProperty.FindNavigation(nameof(EntityWithOneProperty.EntityWithTwoProperties))! .ForeignKey; var ownedType1 = ownership1.DeclaringEntityType; Assert.Equal(nameof(EntityWithOneProperty), ownedType1.GetTableName()); @@ -4813,24 +4813,24 @@ public virtual void Owned_types_mapped_to_json_with_explicit_column_type_are_sto private class Order { public int Id { get; set; } - public OrderDetails OrderBillingDetails { get; set; } - public OrderDetails OrderShippingDetails { get; set; } - public OrderInfo OrderInfo { get; set; } + public OrderDetails? OrderBillingDetails { get; set; } + public OrderDetails? OrderShippingDetails { get; set; } + public OrderInfo? OrderInfo { get; set; } } private class OrderDetails { - public StreetAddress StreetAddress { get; set; } + public StreetAddress? StreetAddress { get; set; } } private class OrderInfo { - public StreetAddress StreetAddress { get; set; } + public StreetAddress? StreetAddress { get; set; } } private class StreetAddress { - public string City { get; set; } + public string? City { get; set; } } #endregion @@ -4865,7 +4865,7 @@ public virtual void Property_annotations_are_stored_in_snapshot() b.ToTable("EntityWithOneProperty", "DefaultSchema"); }); """), - o => Assert.Equal("AnnotationValue", o.GetEntityTypes().First().FindProperty("Id")["AnnotationName"]) + o => Assert.Equal("AnnotationValue", o.GetEntityTypes().First().FindProperty("Id")!["AnnotationName"]) ); [Fact] @@ -4892,7 +4892,7 @@ public virtual void Custom_value_generator_is_ignored_in_snapshot() b.ToTable("EntityWithOneProperty", "DefaultSchema"); }); """), - o => Assert.Null(o.GetEntityTypes().First().FindProperty("Id")[CoreAnnotationNames.ValueGeneratorFactory]) + o => Assert.Null(o.GetEntityTypes().First().FindProperty("Id")![CoreAnnotationNames.ValueGeneratorFactory]) ); [Fact] @@ -4919,7 +4919,7 @@ public virtual void Property_isNullable_is_stored_in_snapshot() b.ToTable("EntityWithStringProperty", "DefaultSchema"); }); """), - o => Assert.False(o.GetEntityTypes().First().FindProperty("Name").IsNullable)); + o => Assert.False(o.GetEntityTypes().First().FindProperty("Name")!.IsNullable)); [Fact] public virtual void Property_ValueGenerated_value_is_stored_in_snapshot() @@ -4950,7 +4950,7 @@ public virtual void Property_ValueGenerated_value_is_stored_in_snapshot() b.ToTable("EntityWithTwoProperties", "DefaultSchema"); }); """, usingSystem: true), - o => Assert.Equal(ValueGenerated.OnAdd, o.GetEntityTypes().First().FindProperty("AlternateId").ValueGenerated)); + o => Assert.Equal(ValueGenerated.OnAdd, o.GetEntityTypes().First().FindProperty("AlternateId")!.ValueGenerated)); [Fact] public virtual void Property_ValueGenerated_non_identity() @@ -5015,7 +5015,7 @@ public virtual void Property_maxLength_is_stored_in_snapshot() b.ToTable("EntityWithStringProperty", "DefaultSchema"); }); """), - o => Assert.Equal(100, o.GetEntityTypes().First().FindProperty("Name").GetMaxLength())); + o => Assert.Equal(100, o.GetEntityTypes().First().FindProperty("Name")!.GetMaxLength())); [Fact] public virtual void Property_maximum_maxLength_is_stored_in_snapshot() @@ -5041,7 +5041,7 @@ public virtual void Property_maximum_maxLength_is_stored_in_snapshot() b.ToTable("EntityWithStringProperty", "DefaultSchema"); }); """), - o => Assert.Equal(-1, o.GetEntityTypes().First().FindProperty("Name").GetMaxLength())); + o => Assert.Equal(-1, o.GetEntityTypes().First().FindProperty("Name")!.GetMaxLength())); [Fact] public virtual void Property_unicodeness_is_stored_in_snapshot() @@ -5067,7 +5067,7 @@ public virtual void Property_unicodeness_is_stored_in_snapshot() b.ToTable("EntityWithStringProperty", "DefaultSchema"); }); """), - o => Assert.False(o.GetEntityTypes().First().FindProperty("Name").IsUnicode())); + o => Assert.False(o.GetEntityTypes().First().FindProperty("Name")!.IsUnicode())); [Fact] public virtual void Property_fixedlengthness_is_stored_in_snapshot() @@ -5094,7 +5094,7 @@ public virtual void Property_fixedlengthness_is_stored_in_snapshot() b.ToTable("EntityWithStringProperty", "DefaultSchema"); }); """), - o => Assert.True(o.GetEntityTypes().First().FindProperty("Name").IsFixedLength())); + o => Assert.True(o.GetEntityTypes().First().FindProperty("Name")!.IsFixedLength())); [Fact] public virtual void Property_precision_is_stored_in_snapshot() @@ -5125,7 +5125,7 @@ public virtual void Property_precision_is_stored_in_snapshot() """), o => { - var property = o.GetEntityTypes().First().FindProperty(nameof(EntityWithDecimalProperty.Price)); + var property = o.GetEntityTypes().First().FindProperty(nameof(EntityWithDecimalProperty.Price))!; Assert.Equal(7, property.GetPrecision()); Assert.Null(property.GetScale()); }); @@ -5159,7 +5159,7 @@ public virtual void Property_precision_and_scale_is_stored_in_snapshot() """), o => { - var property = o.GetEntityTypes().First().FindProperty(nameof(EntityWithDecimalProperty.Price)); + var property = o.GetEntityTypes().First().FindProperty(nameof(EntityWithDecimalProperty.Price))!; Assert.Equal(7, property.GetPrecision()); Assert.Equal(3, property.GetScale()); }); @@ -5196,7 +5196,7 @@ public virtual void Many_facets_chained_in_snapshot() """), o => { - var property = o.GetEntityTypes().First().FindProperty("Name"); + var property = o.GetEntityTypes().First().FindProperty("Name")!; Assert.Equal(100, property.GetMaxLength()); Assert.False(property.IsUnicode()); Assert.Equal("AnnotationValue", property["AnnotationName"]); @@ -5230,7 +5230,7 @@ public virtual void Property_concurrencyToken_is_stored_in_snapshot() b.ToTable("EntityWithTwoProperties", "DefaultSchema"); }); """), - o => Assert.True(o.GetEntityTypes().First().FindProperty("AlternateId").IsConcurrencyToken)); + o => Assert.True(o.GetEntityTypes().First().FindProperty("AlternateId")!.IsConcurrencyToken)); [Fact] public virtual void Property_column_name_annotation_is_stored_in_snapshot_as_fluent_api() @@ -5260,7 +5260,7 @@ public virtual void Property_column_name_annotation_is_stored_in_snapshot_as_flu b.ToTable("EntityWithTwoProperties", "DefaultSchema"); }); """), - o => Assert.Equal("CName", o.GetEntityTypes().First().FindProperty("AlternateId")["Relational:ColumnName"])); + o => Assert.Equal("CName", o.GetEntityTypes().First().FindProperty("AlternateId")!["Relational:ColumnName"])); [Fact] public virtual void Property_column_name_is_stored_in_snapshot_when_DefaultColumnName_uses_clr_type() @@ -5340,7 +5340,7 @@ public virtual void Property_column_name_is_stored_in_snapshot_when_DefaultColum """), model => { - var entityType = model.FindEntityType(typeof(BarA).FullName); + var entityType = model.FindEntityType(typeof(BarA).FullName!)!; Assert.NotNull(entityType); var property = entityType.FindProperty("FooExtensionId"); @@ -5554,7 +5554,7 @@ public virtual void Property_column_name_on_specific_table_is_stored_in_snapshot "Microsoft.EntityFrameworkCore.Migrations.Design.CSharpMigrationsGeneratorTest+DuplicateDerivedEntity", t.Name); Assert.Equal( "DuplicateDerivedEntity_Name", - t.FindProperty(nameof(DuplicateDerivedEntity.Name)) + t.FindProperty(nameof(DuplicateDerivedEntity.Name))! .GetColumnName(StoreObjectIdentifier.Table(nameof(BaseEntity), "DefaultSchema"))); } ); @@ -5587,7 +5587,7 @@ public virtual void Property_column_type_annotation_is_stored_in_snapshot_as_flu b.ToTable("EntityWithTwoProperties", "DefaultSchema"); }); """), - o => Assert.Equal("CType", o.GetEntityTypes().First().FindProperty("AlternateId")["Relational:ColumnType"])); + o => Assert.Equal("CType", o.GetEntityTypes().First().FindProperty("AlternateId")!["Relational:ColumnType"])); [Fact] public virtual void Property_default_value_annotation_is_stored_in_snapshot_as_fluent_api() @@ -5618,7 +5618,7 @@ public virtual void Property_default_value_annotation_is_stored_in_snapshot_as_f b.ToTable("EntityWithTwoProperties", "DefaultSchema"); }); """), - o => Assert.Equal(1, o.GetEntityTypes().First().FindProperty("AlternateId")["Relational:DefaultValue"])); + o => Assert.Equal(1, o.GetEntityTypes().First().FindProperty("AlternateId")!["Relational:DefaultValue"])); [Fact] public virtual void Property_default_value_annotation_is_stored_in_snapshot_as_fluent_api_unspecified() @@ -5650,7 +5650,7 @@ public virtual void Property_default_value_annotation_is_stored_in_snapshot_as_f }); """, usingSystem: true), - o => Assert.Equal(DBNull.Value, o.GetEntityTypes().First().FindProperty("AlternateId")["Relational:DefaultValue"])); + o => Assert.Equal(DBNull.Value, o.GetEntityTypes().First().FindProperty("AlternateId")!["Relational:DefaultValue"])); [Fact] public virtual void Property_default_value_sql_annotation_is_stored_in_snapshot_as_fluent_api_unspecified() @@ -5681,7 +5681,7 @@ public virtual void Property_default_value_sql_annotation_is_stored_in_snapshot_ b.ToTable("EntityWithTwoProperties", "DefaultSchema"); }); """), - o => Assert.Equal(string.Empty, o.GetEntityTypes().First().FindProperty("AlternateId")["Relational:DefaultValueSql"])); + o => Assert.Equal(string.Empty, o.GetEntityTypes().First().FindProperty("AlternateId")!["Relational:DefaultValueSql"])); [Fact] public virtual void Property_default_value_sql_annotation_is_stored_in_snapshot_as_fluent_api() @@ -5712,7 +5712,7 @@ public virtual void Property_default_value_sql_annotation_is_stored_in_snapshot_ b.ToTable("EntityWithTwoProperties", "DefaultSchema"); }); """), - o => Assert.Equal("SQL", o.GetEntityTypes().First().FindProperty("AlternateId")["Relational:DefaultValueSql"])); + o => Assert.Equal("SQL", o.GetEntityTypes().First().FindProperty("AlternateId")!["Relational:DefaultValueSql"])); [Fact] public virtual void Property_computed_column_sql_annotation_is_stored_in_snapshot_as_fluent_api() @@ -5743,7 +5743,7 @@ public virtual void Property_computed_column_sql_annotation_is_stored_in_snapsho b.ToTable("EntityWithTwoProperties", "DefaultSchema"); }); """), - o => Assert.Equal("SQL", o.GetEntityTypes().First().FindProperty("AlternateId")["Relational:ComputedColumnSql"])); + o => Assert.Equal("SQL", o.GetEntityTypes().First().FindProperty("AlternateId")!["Relational:ComputedColumnSql"])); [Fact] public virtual void Property_computed_column_sql_stored_annotation_is_stored_in_snapshot_as_fluent_api() @@ -5776,8 +5776,8 @@ public virtual void Property_computed_column_sql_stored_annotation_is_stored_in_ """), o => { - Assert.Equal("SQL", o.GetEntityTypes().First().FindProperty("AlternateId")["Relational:ComputedColumnSql"]); - Assert.Equal(true, o.GetEntityTypes().First().FindProperty("AlternateId")["Relational:IsStored"]); + Assert.Equal("SQL", o.GetEntityTypes().First().FindProperty("AlternateId")!["Relational:ComputedColumnSql"]); + Assert.Equal(true, o.GetEntityTypes().First().FindProperty("AlternateId")!["Relational:IsStored"]); }); [Fact] @@ -5809,7 +5809,7 @@ public virtual void Property_computed_column_sql_annotation_is_stored_in_snapsho b.ToTable("EntityWithTwoProperties", "DefaultSchema"); }); """), - o => Assert.Equal(string.Empty, o.GetEntityTypes().First().FindProperty("AlternateId")["Relational:ComputedColumnSql"])); + o => Assert.Equal(string.Empty, o.GetEntityTypes().First().FindProperty("AlternateId")!["Relational:ComputedColumnSql"])); [Fact] public virtual void Property_default_value_of_enum_type_is_stored_in_snapshot_without_actual_enum() @@ -5836,7 +5836,7 @@ public virtual void Property_default_value_of_enum_type_is_stored_in_snapshot_wi b.ToTable("EntityWithEnumType", "DefaultSchema"); }); """), - o => Assert.Equal(3L, o.GetEntityTypes().First().FindProperty("Day")["Relational:DefaultValue"])); + o => Assert.Equal(3L, o.GetEntityTypes().First().FindProperty("Day")!["Relational:DefaultValue"])); [Fact] public virtual void Property_enum_type_is_stored_in_snapshot_with_custom_conversion_and_seed_data() @@ -5880,7 +5880,7 @@ public virtual void Property_enum_type_is_stored_in_snapshot_with_custom_convers o => { var property = o.GetEntityTypes().First().FindProperty("Day"); - Assert.Equal(typeof(string), property.ClrType); + Assert.Equal(typeof(string), property!.ClrType); Assert.Equal(nameof(Days.Wed), property["Relational:DefaultValue"]); Assert.False(property.IsNullable); }); @@ -5909,7 +5909,7 @@ public virtual void Property_of_nullable_enum() b.ToTable("EntityWithNullableEnumType", "DefaultSchema"); }); """), - o => Assert.True(o.GetEntityTypes().First().FindProperty("Day").IsNullable)); + o => Assert.True(o.GetEntityTypes().First().FindProperty("Day")!.IsNullable)); [Fact] public virtual void Property_of_enum_to_nullable() @@ -5935,7 +5935,7 @@ public virtual void Property_of_enum_to_nullable() b.ToTable("EntityWithEnumType", "DefaultSchema"); }); """), - o => Assert.False(o.GetEntityTypes().First().FindProperty("Day").IsNullable)); + o => Assert.False(o.GetEntityTypes().First().FindProperty("Day")!.IsNullable)); [Fact] public virtual void Property_of_nullable_enum_to_string() @@ -5960,7 +5960,7 @@ public virtual void Property_of_nullable_enum_to_string() b.ToTable("EntityWithNullableEnumType", "DefaultSchema"); }); """), - o => Assert.True(o.GetEntityTypes().First().FindProperty("Day").IsNullable)); + o => Assert.True(o.GetEntityTypes().First().FindProperty("Day")!.IsNullable)); [Fact] public virtual void Property_multiple_annotations_are_stored_in_snapshot() @@ -5995,7 +5995,7 @@ public virtual void Property_multiple_annotations_are_stored_in_snapshot() o => { var property = o.GetEntityTypes().First().FindProperty("AlternateId"); - Assert.Equal(3, property.GetAnnotations().Count()); + Assert.Equal(3, property!.GetAnnotations().Count()); Assert.Equal("AnnotationValue", property["AnnotationName"]); Assert.Equal("CName", property["Relational:ColumnName"]); Assert.Equal("int", property["Relational:ColumnType"]); @@ -6040,7 +6040,7 @@ public virtual void Property_without_column_type() """), o => { - var property = o.FindEntityType("Building").FindProperty("Id"); + var property = o.FindEntityType("Building")!.FindProperty("Id")!; Assert.Equal("int", property.GetColumnType()); }); @@ -6074,7 +6074,7 @@ public virtual void Property_with_identity_column() """), o => { - var property = o.FindEntityType("Building").FindProperty("Id"); + var property = o.FindEntityType("Building")!.FindProperty("Id")!; Assert.Equal( SqlServerValueGenerationStrategy.IdentityColumn, SqlServerPropertyExtensions.GetValueGenerationStrategy(property)); Assert.Equal(1, property.GetIdentitySeed()); @@ -6111,7 +6111,7 @@ public virtual void Property_with_identity_column_custom_seed() """), o => { - var property = o.FindEntityType("Building").FindProperty("Id"); + var property = o.FindEntityType("Building")!.FindProperty("Id")!; Assert.Equal( SqlServerValueGenerationStrategy.IdentityColumn, SqlServerPropertyExtensions.GetValueGenerationStrategy(property)); Assert.Equal(5, property.GetIdentitySeed()); @@ -6148,7 +6148,7 @@ public virtual void Property_with_identity_column_custom_increment() """), o => { - var property = o.FindEntityType("Building").FindProperty("Id"); + var property = o.FindEntityType("Building")!.FindProperty("Id")!; Assert.Equal( SqlServerValueGenerationStrategy.IdentityColumn, SqlServerPropertyExtensions.GetValueGenerationStrategy(property)); Assert.Equal(1, property.GetIdentitySeed()); @@ -6185,7 +6185,7 @@ public virtual void Property_with_identity_column_custom_seed_increment() """), o => { - var property = o.FindEntityType("Building").FindProperty("Id"); + var property = o.FindEntityType("Building")!.FindProperty("Id")!; Assert.Equal( SqlServerValueGenerationStrategy.IdentityColumn, SqlServerPropertyExtensions.GetValueGenerationStrategy(property)); Assert.Equal(5, property.GetIdentitySeed()); @@ -6220,7 +6220,7 @@ public virtual void Property_column_order_annotation_is_stored_in_snapshot_as_fl b.ToTable("EntityWithTwoProperties", "DefaultSchema"); }); """), - o => Assert.Equal(1, o.GetEntityTypes().First().FindProperty("AlternateId").GetColumnOrder())); + o => Assert.Equal(1, o.GetEntityTypes().First().FindProperty("AlternateId")!.GetColumnOrder())); [Fact] public virtual void SQLServer_model_legacy_identity_seed_int_annotation() @@ -6264,7 +6264,7 @@ public virtual void SQLServer_property_legacy_identity_seed_int_annotation() b.ToTable("EntityWithTwoProperties", "DefaultSchema"); }); """), - o => Assert.Equal(8L, o.GetEntityTypes().First().FindProperty("Id").GetIdentitySeed())); + o => Assert.Equal(8L, o.GetEntityTypes().First().FindProperty("Id")!.GetIdentitySeed())); #endregion @@ -6329,7 +6329,7 @@ public virtual void PrimitiveCollection_is_stored_in_snapshot() """), o => { - var property = o.GetEntityTypes().First().FindProperty("List"); + var property = o.GetEntityTypes().First().FindProperty("List")!; Assert.Equal("AnnotationValue", property["AnnotationName"]); }); @@ -6426,10 +6426,10 @@ public virtual void Complex_properties_are_stored_in_snapshot() """, usingCollections: true), (_, o) => { - var entityWithOneProperty = o.FindEntityType(typeof(EntityWithOneProperty)); + var entityWithOneProperty = o.FindEntityType(typeof(EntityWithOneProperty))!; Assert.Equal(nameof(EntityWithOneProperty), entityWithOneProperty.GetTableName()); - var complexProperty = entityWithOneProperty.FindComplexProperty(nameof(EntityWithOneProperty.EntityWithTwoProperties)); + var complexProperty = entityWithOneProperty.FindComplexProperty(nameof(EntityWithOneProperty.EntityWithTwoProperties))!; Assert.False(complexProperty.IsCollection); Assert.False(complexProperty.IsNullable); var complexType = complexProperty.ComplexType; @@ -6438,12 +6438,12 @@ public virtual void Complex_properties_are_stored_in_snapshot() complexType.Name); Assert.Equal("EntityWithOneProperty.EntityWithTwoProperties#EntityWithTwoProperties", complexType.DisplayName()); Assert.Equal(nameof(EntityWithOneProperty), complexType.GetTableName()); - var alternateIdProperty = complexType.FindProperty(nameof(EntityWithTwoProperties.AlternateId)); + var alternateIdProperty = complexType.FindProperty(nameof(EntityWithTwoProperties.AlternateId))!; Assert.Equal(1, alternateIdProperty.GetColumnOrder()); Assert.Equal(1, complexProperty["PropertyAnnotation"]); Assert.Equal(2, complexProperty.ComplexType["TypeAnnotation"]); - var coordinateComplexProperty = complexType.FindComplexProperty(nameof(EntityWithTwoProperties.Coordinates)); + var coordinateComplexProperty = complexType.FindComplexProperty(nameof(EntityWithTwoProperties.Coordinates))!; Assert.False(coordinateComplexProperty.IsCollection); Assert.False(coordinateComplexProperty.IsNullable); var coordinateComplexType = coordinateComplexProperty.ComplexType; @@ -6453,12 +6453,12 @@ public virtual void Complex_properties_are_stored_in_snapshot() Assert.Equal( "EntityWithOneProperty.EntityWithTwoProperties#EntityWithTwoProperties.Coordinates#Coordinates", coordinateComplexType.DisplayName()); - var coordinateXProperty = coordinateComplexType.FindProperty(nameof(Coordinates.Latitude)); + var coordinateXProperty = coordinateComplexType.FindProperty(nameof(Coordinates.Latitude))!; Assert.Equal("Coordinate_X", coordinateXProperty.GetColumnName()); - var coordinateYProperty = coordinateComplexType.FindProperty(nameof(Coordinates.Longitude)); + var coordinateYProperty = coordinateComplexType.FindProperty(nameof(Coordinates.Longitude))!; Assert.Equal("Coordinate_Y", coordinateYProperty.GetColumnName()); - var nestedComplexProperty = complexType.FindComplexProperty(nameof(EntityWithTwoProperties.EntityWithStringKey)); + var nestedComplexProperty = complexType.FindComplexProperty(nameof(EntityWithTwoProperties.EntityWithStringKey))!; Assert.False(nestedComplexProperty.IsCollection); Assert.True(nestedComplexProperty.IsNullable); var nestedComplexType = nestedComplexProperty.ComplexType; @@ -6469,7 +6469,7 @@ public virtual void Complex_properties_are_stored_in_snapshot() "EntityWithOneProperty.EntityWithTwoProperties#EntityWithTwoProperties.EntityWithStringKey#EntityWithStringKey", nestedComplexType.DisplayName()); Assert.Equal(nameof(EntityWithOneProperty), nestedComplexType.GetTableName()); - var nestedIdProperty = nestedComplexType.FindProperty(nameof(EntityWithStringKey.Id)); + var nestedIdProperty = nestedComplexType.FindProperty(nameof(EntityWithStringKey.Id))!; Assert.False(nestedIdProperty.IsNullable); }, validate: true); @@ -6577,37 +6577,37 @@ public virtual void Complex_types_mapped_to_json_are_stored_in_snapshot() """, usingSystem: false, usingCollections: true), o => { - var entityWithOneProperty = o.FindEntityType(typeof(EntityWithOneProperty)); + var entityWithOneProperty = o.FindEntityType(typeof(EntityWithOneProperty))!; Assert.Equal("PK_Custom", entityWithOneProperty.GetKeys().Single().GetName()); - var complexProperty1 = entityWithOneProperty.FindComplexProperty(nameof(EntityWithOneProperty.EntityWithTwoProperties)); + var complexProperty1 = entityWithOneProperty.FindComplexProperty(nameof(EntityWithOneProperty.EntityWithTwoProperties))!; Assert.False(complexProperty1.IsCollection); Assert.True(complexProperty1.IsNullable); var complexType1 = complexProperty1.ComplexType; Assert.Equal("TwoProps", complexType1.GetContainerColumnName()); Assert.Equal("nvarchar(max)", complexType1.GetContainerColumnType()); - var alternateIdProperty = complexType1.FindProperty(nameof(EntityWithTwoProperties.AlternateId)); + var alternateIdProperty = complexType1.FindProperty(nameof(EntityWithTwoProperties.AlternateId))!; Assert.Equal("NotKey", alternateIdProperty.GetJsonPropertyName()); - var coordinatesComplexProperty = complexType1.FindComplexProperty(nameof(EntityWithTwoProperties.Coordinates)); + var coordinatesComplexProperty = complexType1.FindComplexProperty(nameof(EntityWithTwoProperties.Coordinates))!; Assert.False(coordinatesComplexProperty.IsCollection); Assert.False(coordinatesComplexProperty.IsNullable); var coordinatesComplexType = coordinatesComplexProperty.ComplexType; - var latitudeProperty = coordinatesComplexType.FindProperty(nameof(Coordinates.Latitude)); + var latitudeProperty = coordinatesComplexType.FindProperty(nameof(Coordinates.Latitude))!; Assert.Equal("Lat", latitudeProperty.GetJsonPropertyName()); - var longitudeProperty = coordinatesComplexType.FindProperty(nameof(Coordinates.Longitude)); + var longitudeProperty = coordinatesComplexType.FindProperty(nameof(Coordinates.Longitude))!; Assert.Equal("Lon", longitudeProperty.GetJsonPropertyName()); var entityWithStringKeyComplexProperty = - complexType1.FindComplexProperty(nameof(EntityWithTwoProperties.EntityWithStringKey)); + complexType1.FindComplexProperty(nameof(EntityWithTwoProperties.EntityWithStringKey))!; Assert.False(entityWithStringKeyComplexProperty.IsCollection); Assert.True(entityWithStringKeyComplexProperty.IsNullable); var entityWithStringKeyComplexType = entityWithStringKeyComplexProperty.ComplexType; Assert.Equal("Terminator", entityWithStringKeyComplexType.FindDiscriminatorProperty()!.GetJsonPropertyName()); var propertiesComplexCollection = - entityWithStringKeyComplexType.FindComplexProperty(nameof(EntityWithStringKey.Properties)); + entityWithStringKeyComplexType.FindComplexProperty(nameof(EntityWithStringKey.Properties))!; Assert.True(propertiesComplexCollection.IsCollection); Assert.Equal("JsonProps", propertiesComplexCollection.GetJsonPropertyName()); Assert.Equal(typeof(List>), propertiesComplexCollection.ClrType); @@ -6692,36 +6692,36 @@ public virtual void Complex_types_mapped_to_json_with_explicit_column_type_are_s """, usingSystem: false, usingCollections: true), o => { - var entityWithOneProperty = o.FindEntityType(typeof(EntityWithOneProperty)); + var entityWithOneProperty = o.FindEntityType(typeof(EntityWithOneProperty))!; Assert.Equal("PK_Custom", entityWithOneProperty.GetKeys().Single().GetName()); - var complexProperty1 = entityWithOneProperty.FindComplexProperty(nameof(EntityWithOneProperty.EntityWithTwoProperties)); + var complexProperty1 = entityWithOneProperty.FindComplexProperty(nameof(EntityWithOneProperty.EntityWithTwoProperties))!; Assert.False(complexProperty1.IsCollection); Assert.True(complexProperty1.IsNullable); var complexType1 = complexProperty1.ComplexType; Assert.Equal("TwoProps", complexType1.GetContainerColumnName()); Assert.Equal("json", complexType1.GetContainerColumnType()); - var alternateIdProperty = complexType1.FindProperty(nameof(EntityWithTwoProperties.AlternateId)); + var alternateIdProperty = complexType1.FindProperty(nameof(EntityWithTwoProperties.AlternateId))!; Assert.Equal("NotKey", alternateIdProperty.GetJsonPropertyName()); - var coordinatesComplexProperty = complexType1.FindComplexProperty(nameof(EntityWithTwoProperties.Coordinates)); + var coordinatesComplexProperty = complexType1.FindComplexProperty(nameof(EntityWithTwoProperties.Coordinates))!; Assert.False(coordinatesComplexProperty.IsCollection); Assert.False(coordinatesComplexProperty.IsNullable); var coordinatesComplexType = coordinatesComplexProperty.ComplexType; - var latitudeProperty = coordinatesComplexType.FindProperty(nameof(Coordinates.Latitude)); + var latitudeProperty = coordinatesComplexType.FindProperty(nameof(Coordinates.Latitude))!; Assert.Equal("Lat", latitudeProperty.GetJsonPropertyName()); - var longitudeProperty = coordinatesComplexType.FindProperty(nameof(Coordinates.Longitude)); + var longitudeProperty = coordinatesComplexType.FindProperty(nameof(Coordinates.Longitude))!; Assert.Equal("Lon", longitudeProperty.GetJsonPropertyName()); var entityWithStringKeyComplexProperty = - complexType1.FindComplexProperty(nameof(EntityWithTwoProperties.EntityWithStringKey)); + complexType1.FindComplexProperty(nameof(EntityWithTwoProperties.EntityWithStringKey))!; Assert.False(entityWithStringKeyComplexProperty.IsCollection); Assert.True(entityWithStringKeyComplexProperty.IsNullable); var entityWithStringKeyComplexType = entityWithStringKeyComplexProperty.ComplexType; var propertiesComplexCollection = - entityWithStringKeyComplexType.FindComplexProperty(nameof(EntityWithStringKey.Properties)); + entityWithStringKeyComplexType.FindComplexProperty(nameof(EntityWithStringKey.Properties))!; Assert.True(propertiesComplexCollection.IsCollection); Assert.Equal("JsonProps", propertiesComplexCollection.GetJsonPropertyName()); Assert.Equal(typeof(List>), propertiesComplexCollection.ClrType); @@ -6800,20 +6800,20 @@ public virtual void Complex_collection_property_annotations_not_supported_by_bui """, usingSystem: false, usingCollections: true), o => { - var entityWithOneProperty = o.FindEntityType(typeof(EntityWithOneProperty)); - var complexProperty1 = entityWithOneProperty.FindComplexProperty(nameof(EntityWithOneProperty.EntityWithTwoProperties)); + var entityWithOneProperty = o.FindEntityType(typeof(EntityWithOneProperty))!; + var complexProperty1 = entityWithOneProperty.FindComplexProperty(nameof(EntityWithOneProperty.EntityWithTwoProperties))!; var complexType1 = complexProperty1.ComplexType; var entityWithStringKeyComplexProperty = - complexType1.FindComplexProperty(nameof(EntityWithTwoProperties.EntityWithStringKey)); + complexType1.FindComplexProperty(nameof(EntityWithTwoProperties.EntityWithStringKey))!; var entityWithStringKeyComplexType = entityWithStringKeyComplexProperty.ComplexType; var propertiesComplexCollection = - entityWithStringKeyComplexType.FindComplexProperty(nameof(EntityWithStringKey.Properties)); + entityWithStringKeyComplexType.FindComplexProperty(nameof(EntityWithStringKey.Properties))!; Assert.True(propertiesComplexCollection.IsCollection); // MaxLength is NOT in the snapshot, so it won't be set on the model created from snapshot // This verifies that the snapshot doesn't contain HasMaxLength which would cause a compile error - var nameProperty = propertiesComplexCollection.ComplexType.FindProperty("Name"); + var nameProperty = propertiesComplexCollection.ComplexType.FindProperty("Name")!; Assert.Null(nameProperty.GetMaxLength()); }); @@ -7376,7 +7376,7 @@ public virtual void Index_with_default_constraint_name_exceeding_max() b.ToTable("EntityWithStringProperty", "DefaultSchema"); }); """), - model => Assert.Equal(128, model.GetEntityTypes().First().GetIndexes().First().GetDatabaseName().Length)); + model => Assert.Equal(128, model.GetEntityTypes().First().GetIndexes().First().GetDatabaseName()!.Length)); [Fact] public virtual void IndexAttribute_causes_column_to_have_key_or_index_column_length() @@ -7547,7 +7547,7 @@ public virtual void IndexAttribute_IncludeProperties_generated_without_fluent_ap model => { var index = model.GetEntityTypes().First().GetIndexes().First(); - Assert.Equal("Name", Assert.Single(index.GetIncludeProperties())); + Assert.Equal("Name", Assert.Single(index.GetIncludeProperties()!)); }); [Fact] @@ -7652,21 +7652,21 @@ public virtual void IndexAttribute_SortInTempDb_is_stored_in_snapshot() private class SnapshotBlog { public int Id { get; set; } - public string Title { get; set; } - public List Posts { get; set; } = []; - public SnapshotAddress Owner { get; set; } + public string? Title { get; set; } + public List? Posts { get; set; } = []; + public SnapshotAddress? Owner { get; set; } } private class SnapshotPost { - public string Title { get; set; } + public string? Title { get; set; } public int Rating { get; set; } } private class SnapshotAddress { - public string City { get; set; } - public string Country { get; set; } + public string? City { get; set; } + public string? Country { get; set; } } [Fact] @@ -7689,13 +7689,13 @@ public void Snapshot_emits_dotted_path_for_index_through_complex_property() cb.Property(p => p.Rating); cb.ToJson(); }); - eb.HasIndex(e => e.Owner.City); + eb.HasIndex(e => e.Owner!.City); }), """b.HasIndex("Owner.City")""", model => Assert.Equal( "City", Assert.Single( - model.FindEntityType(typeof(SnapshotBlog)).GetIndexes(), + model.FindEntityType(typeof(SnapshotBlog))!.GetIndexes(), i => i.CollectionIndices is null).Properties.Single().Name), fullSnapshot: false); @@ -7719,14 +7719,14 @@ public void Snapshot_emits_empty_brackets_for_index_through_complex_collection() cb.Property(p => p.Rating); cb.ToJson(); }); - eb.HasIndex(e => e.Posts.Select(p => p.Title)); + eb.HasIndex(e => e.Posts!.Select(p => p.Title)); }), """b.HasIndex("Posts[].Title")""", model => { - var index = model.FindEntityType(typeof(SnapshotBlog)).GetIndexes().Single(); + var index = model.FindEntityType(typeof(SnapshotBlog))!.GetIndexes().Single(); Assert.Equal("Title", index.Properties.Single().Name); - Assert.Equal(new int?[] { null }, Assert.Single(index.CollectionIndices)); + Assert.Equal(new int?[] { null }, Assert.Single(index.CollectionIndices!)); }, fullSnapshot: false); @@ -7750,14 +7750,14 @@ public void Snapshot_emits_numeric_bracket_for_index_through_complex_collection_ cb.Property(p => p.Rating); cb.ToJson(); }); - eb.HasIndex(e => e.Posts[0].Rating); + eb.HasIndex(e => e.Posts![0].Rating); }), """b.HasIndex("Posts[0].Rating")""", model => { - var index = model.FindEntityType(typeof(SnapshotBlog)).GetIndexes().Single(); + var index = model.FindEntityType(typeof(SnapshotBlog))!.GetIndexes().Single(); Assert.Equal("Rating", index.Properties.Single().Name); - Assert.Equal(new int?[] { 0 }, Assert.Single(index.CollectionIndices)); + Assert.Equal(new int?[] { 0 }, Assert.Single(index.CollectionIndices!)); }, fullSnapshot: false); @@ -7781,7 +7781,7 @@ public virtual void Index_through_complex_property_is_stored_in_snapshot() cb.Property(p => p.Rating); cb.ToJson(); }); - eb.HasIndex(e => e.Owner.City); + eb.HasIndex(e => e.Owner!.City); }), AddBoilerPlate( GetHeading() @@ -7828,7 +7828,7 @@ public virtual void Index_through_complex_property_is_stored_in_snapshot() """, usingCollections: true), model => { - var index = Assert.Single(model.FindEntityType(typeof(SnapshotBlog)).GetIndexes()); + var index = Assert.Single(model.FindEntityType(typeof(SnapshotBlog))!.GetIndexes()); Assert.Equal("City", index.Properties.Single().Name); Assert.Null(index.CollectionIndices); }); @@ -7853,7 +7853,7 @@ public virtual void Index_through_complex_collection_all_elements_is_stored_in_s cb.Property(p => p.Rating); cb.ToJson(); }); - eb.HasIndex(e => e.Posts.Select(p => p.Title)); + eb.HasIndex(e => e.Posts!.Select(p => p.Title)); }), AddBoilerPlate( GetHeading() @@ -7900,7 +7900,7 @@ public virtual void Index_through_complex_collection_all_elements_is_stored_in_s """, usingCollections: true), model => { - var index = Assert.Single(model.FindEntityType(typeof(SnapshotBlog)).GetIndexes()); + var index = Assert.Single(model.FindEntityType(typeof(SnapshotBlog))!.GetIndexes()); Assert.Equal("Title", index.Properties.Single().Name); Assert.Equal(new int?[] { null }, Assert.Single(index.CollectionIndices!)); }); @@ -7925,7 +7925,7 @@ public virtual void Index_through_complex_collection_indexer_is_stored_in_snapsh cb.Property(p => p.Rating); cb.ToJson(); }); - eb.HasIndex(e => e.Posts[0].Rating); + eb.HasIndex(e => e.Posts![0].Rating); }), AddBoilerPlate( GetHeading() @@ -7972,7 +7972,7 @@ public virtual void Index_through_complex_collection_indexer_is_stored_in_snapsh """, usingCollections: true), model => { - var index = Assert.Single(model.FindEntityType(typeof(SnapshotBlog)).GetIndexes()); + var index = Assert.Single(model.FindEntityType(typeof(SnapshotBlog))!.GetIndexes()); Assert.Equal("Rating", index.Properties.Single().Name); Assert.Equal(new int?[] { 0 }, Assert.Single(index.CollectionIndices!)); }); @@ -8042,7 +8042,7 @@ public virtual void ForeignKey_annotations_are_stored_in_snapshot() }); """), o => Assert.Equal( - "AnnotationValue", o.FindEntityType(typeof(EntityWithTwoProperties)).GetForeignKeys().First()["AnnotationName"])); + "AnnotationValue", o.FindEntityType(typeof(EntityWithTwoProperties))!.GetForeignKeys().First()["AnnotationName"])); [Fact] public virtual void ForeignKey_isRequired_is_stored_in_snapshot() @@ -8098,7 +8098,7 @@ public virtual void ForeignKey_isRequired_is_stored_in_snapshot() .IsRequired(); }); """), - o => Assert.False(o.FindEntityType(typeof(EntityWithStringProperty)).FindProperty("Name").IsNullable)); + o => Assert.False(o.FindEntityType(typeof(EntityWithStringProperty))!.FindProperty("Name")!.IsNullable)); [Fact] public virtual void ForeignKey_isUnique_is_stored_in_snapshot() @@ -8150,7 +8150,7 @@ public virtual void ForeignKey_isUnique_is_stored_in_snapshot() b.Navigation("Properties"); }); """), - o => Assert.False(o.FindEntityType(typeof(EntityWithStringProperty)).GetForeignKeys().First().IsUnique)); + o => Assert.False(o.FindEntityType(typeof(EntityWithStringProperty))!.GetForeignKeys().First().IsUnique)); [Fact] public virtual void ForeignKey_with_non_primary_principal_is_stored_in_snapshot() @@ -8211,7 +8211,7 @@ public virtual void ForeignKey_with_non_primary_principal_is_stored_in_snapshot( b.Navigation("Properties"); }); """), - o => Assert.False(o.FindEntityType(typeof(EntityWithStringProperty)).GetForeignKeys().First().IsUnique)); + o => Assert.False(o.FindEntityType(typeof(EntityWithStringProperty))!.GetForeignKeys().First().IsUnique)); [Fact] public virtual void ForeignKey_deleteBehavior_is_stored_in_snapshot() @@ -8265,7 +8265,7 @@ public virtual void ForeignKey_deleteBehavior_is_stored_in_snapshot() }); """), o => Assert.Equal( - DeleteBehavior.Cascade, o.FindEntityType(typeof(EntityWithOneProperty)).GetForeignKeys().First().DeleteBehavior)); + DeleteBehavior.Cascade, o.FindEntityType(typeof(EntityWithOneProperty))!.GetForeignKeys().First().DeleteBehavior)); [Fact] public virtual void ForeignKey_deleteBehavior_is_stored_in_snapshot_for_one_to_one() @@ -8320,12 +8320,12 @@ public virtual void ForeignKey_deleteBehavior_is_stored_in_snapshot_for_one_to_o }); """), o => Assert.Equal( - DeleteBehavior.Cascade, o.FindEntityType(typeof(EntityWithOneProperty)).GetForeignKeys().First().DeleteBehavior)); + DeleteBehavior.Cascade, o.FindEntityType(typeof(EntityWithOneProperty))!.GetForeignKeys().First().DeleteBehavior)); [Fact] public virtual void ForeignKey_name_preserved_when_generic() { - IReadOnlyModel originalModel = null; + IReadOnlyModel originalModel = null!; Test( builder => @@ -8378,27 +8378,27 @@ public virtual void ForeignKey_name_preserved_when_generic() """, usingSystem: true), model => { - var originalParent = originalModel.FindEntityType(typeof(EntityWithGenericKey)); - var parent = model.FindEntityType(originalParent.Name); + var originalParent = originalModel.FindEntityType(typeof(EntityWithGenericKey))!; + var parent = model.FindEntityType(originalParent.Name)!; Assert.NotNull(parent); - var originalChild = originalModel.FindEntityType(typeof(EntityWithGenericProperty)); - var child = model.FindEntityType(originalChild.Name); + var originalChild = originalModel.FindEntityType(typeof(EntityWithGenericProperty))!; + var child = model.FindEntityType(originalChild.Name)!; Assert.NotNull(child); var originalForeignKey = originalChild.FindForeignKey( - originalChild.FindProperty("Property"), - originalParent.FindPrimaryKey(), - originalParent); + originalChild.FindProperty("Property")!, + originalParent.FindPrimaryKey()!, + originalParent)!; var foreignKey = child.FindForeignKey( - child.FindProperty("Property"), - parent.FindPrimaryKey(), - parent); + child.FindProperty("Property")!, + parent.FindPrimaryKey()!, + parent)!; Assert.Equal(originalForeignKey.GetConstraintName(), foreignKey.GetConstraintName()); - var originalIndex = originalChild.FindIndex(originalChild.FindProperty("Property")); - var index = child.FindIndex(child.FindProperty("Property")); + var originalIndex = originalChild.FindIndex(originalChild.FindProperty("Property")!)!; + var index = child.FindIndex(child.FindProperty("Property")!)!; Assert.Equal(originalIndex.GetDatabaseName(), index.GetDatabaseName()); }); @@ -8465,7 +8465,7 @@ public virtual void ForeignKey_constraint_name_is_stored_in_snapshot_as_fluent_a }); """), o => Assert.Equal( - "Constraint", o.FindEntityType(typeof(EntityWithTwoProperties)).GetForeignKeys().First()["Relational:Name"])); + "Constraint", o.FindEntityType(typeof(EntityWithTwoProperties))!.GetForeignKeys().First()["Relational:Name"])); [Fact] public virtual void ForeignKey_excluded_from_migrations_is_stored_in_snapshot() @@ -8528,7 +8528,7 @@ public virtual void ForeignKey_excluded_from_migrations_is_stored_in_snapshot() }); """), o => Assert.True( - o.FindEntityType(typeof(EntityWithTwoProperties)).GetForeignKeys().First().IsExcludedFromMigrations())); + o.FindEntityType(typeof(EntityWithTwoProperties))!.GetForeignKeys().First().IsExcludedFromMigrations())); [Fact] public virtual void ForeignKey_multiple_annotations_are_stored_in_snapshot() @@ -8594,7 +8594,7 @@ public virtual void ForeignKey_multiple_annotations_are_stored_in_snapshot() """), o => { - var fk = o.FindEntityType(typeof(EntityWithTwoProperties)).GetForeignKeys().First(); + var fk = o.FindEntityType(typeof(EntityWithTwoProperties))!.GetForeignKeys().First(); Assert.Equal(2, fk.GetAnnotations().Count()); Assert.Equal("AnnotationValue", fk["AnnotationName"]); Assert.Equal("Constraint", fk["Relational:Name"]); @@ -8726,8 +8726,8 @@ public virtual void ForeignKey_principal_key_is_stored_in_snapshot() """), o => { - Assert.Equal(2, o.FindEntityType(typeof(EntityWithTwoProperties)).GetKeys().Count()); - Assert.True(o.FindEntityType(typeof(EntityWithTwoProperties)).FindProperty("AlternateId").IsKey()); + Assert.Equal(2, o.FindEntityType(typeof(EntityWithTwoProperties))!.GetKeys().Count()); + Assert.True(o.FindEntityType(typeof(EntityWithTwoProperties))!.FindProperty("AlternateId")!.IsKey()); }); [Fact] @@ -8794,10 +8794,10 @@ public virtual void ForeignKey_principal_key_with_non_default_name_is_stored_in_ """), o => { - var entityType = o.FindEntityType(typeof(EntityWithTwoProperties)); + var entityType = o.FindEntityType(typeof(EntityWithTwoProperties))!; Assert.Equal(2, entityType.GetKeys().Count()); - Assert.Equal("Value", entityType.FindKey(entityType.FindProperty("AlternateId"))["Name"]); + Assert.Equal("Value", entityType.FindKey(entityType.FindProperty("AlternateId")!)!["Name"]); }); #endregion @@ -8870,7 +8870,7 @@ public virtual void Navigation_annotations_are_stored_in_snapshot() }); """), o => Assert.Equal( - "AnnotationValue", o.FindEntityType(typeof(EntityWithTwoProperties)).GetNavigations().First()["AnnotationName"])); + "AnnotationValue", o.FindEntityType(typeof(EntityWithTwoProperties))!.GetNavigations().First()["AnnotationName"])); [Fact] public virtual void Navigation_isRequired_is_stored_in_snapshot() @@ -8937,7 +8937,7 @@ public virtual void Navigation_isRequired_is_stored_in_snapshot() .IsRequired(); }); """), - o => Assert.True(o.FindEntityType(typeof(EntityWithOneProperty)).GetNavigations().First().ForeignKey.IsRequiredDependent)); + o => Assert.True(o.FindEntityType(typeof(EntityWithOneProperty))!.GetNavigations().First().ForeignKey.IsRequiredDependent)); #endregion @@ -9416,20 +9416,20 @@ protected override void BuildModel(ModelBuilder modelBuilder) Assert.Equal(point1, seed["SpatialCPoint"]); Assert.Equal(polygon1, seed["SpatialCPolygon"]); - Assert.Equal(4326, ((Geometry)seed["SpatialBGeometryCollection"]).SRID); - Assert.Equal(4326, ((Geometry)seed["SpatialBLineString"]).SRID); - Assert.Equal(4326, ((Geometry)seed["SpatialBMultiLineString"]).SRID); - Assert.Equal(4326, ((Geometry)seed["SpatialBMultiPoint"]).SRID); - Assert.Equal(4326, ((Geometry)seed["SpatialBMultiPolygon"]).SRID); - Assert.Equal(4326, ((Geometry)seed["SpatialBPoint"]).SRID); - Assert.Equal(4326, ((Geometry)seed["SpatialBPolygon"]).SRID); - Assert.Equal(4326, ((Geometry)seed["SpatialCGeometryCollection"]).SRID); - Assert.Equal(4326, ((Geometry)seed["SpatialCLineString"]).SRID); - Assert.Equal(4326, ((Geometry)seed["SpatialCMultiLineString"]).SRID); - Assert.Equal(4326, ((Geometry)seed["SpatialCMultiPoint"]).SRID); - Assert.Equal(4326, ((Geometry)seed["SpatialCMultiPolygon"]).SRID); - Assert.Equal(4326, ((Geometry)seed["SpatialCPoint"]).SRID); - Assert.Equal(4326, ((Geometry)seed["SpatialCPolygon"]).SRID); + Assert.Equal(4326, ((Geometry)seed["SpatialBGeometryCollection"]!).SRID); + Assert.Equal(4326, ((Geometry)seed["SpatialBLineString"]!).SRID); + Assert.Equal(4326, ((Geometry)seed["SpatialBMultiLineString"]!).SRID); + Assert.Equal(4326, ((Geometry)seed["SpatialBMultiPoint"]!).SRID); + Assert.Equal(4326, ((Geometry)seed["SpatialBMultiPolygon"]!).SRID); + Assert.Equal(4326, ((Geometry)seed["SpatialBPoint"]!).SRID); + Assert.Equal(4326, ((Geometry)seed["SpatialBPolygon"]!).SRID); + Assert.Equal(4326, ((Geometry)seed["SpatialCGeometryCollection"]!).SRID); + Assert.Equal(4326, ((Geometry)seed["SpatialCLineString"]!).SRID); + Assert.Equal(4326, ((Geometry)seed["SpatialCMultiLineString"]!).SRID); + Assert.Equal(4326, ((Geometry)seed["SpatialCMultiPoint"]!).SRID); + Assert.Equal(4326, ((Geometry)seed["SpatialCMultiPolygon"]!).SRID); + Assert.Equal(4326, ((Geometry)seed["SpatialCPoint"]!).SRID); + Assert.Equal(4326, ((Geometry)seed["SpatialCPolygon"]!).SRID); Assert.Equal("[1,2,3,4]", seed["Int32Collection"]); Assert.Equal("[1.2,3.4]", seed["DoubleCollection"]); diff --git a/test/EFCore.Design.Tests/Migrations/Design/CSharpMigrationsGeneratorTest.cs b/test/EFCore.Design.Tests/Migrations/Design/CSharpMigrationsGeneratorTest.cs index 48396a73bf8..d563d7c16c8 100644 --- a/test/EFCore.Design.Tests/Migrations/Design/CSharpMigrationsGeneratorTest.cs +++ b/test/EFCore.Design.Tests/Migrations/Design/CSharpMigrationsGeneratorTest.cs @@ -112,8 +112,8 @@ public void Snapshot_with_enum_discriminator_uses_converted_values() var snapshotModel = CompileModelSnapshot(modelSnapshotCode, "MyNamespace.MySnapshot", typeof(MyContext)).Model; - Assert.Equal((int)RawEnum.A, snapshotModel.FindEntityType(typeof(WithAnnotations)).GetDiscriminatorValue()); - Assert.Equal((int)RawEnum.B, snapshotModel.FindEntityType(typeof(Derived)).GetDiscriminatorValue()); + Assert.Equal((int)RawEnum.A, snapshotModel.FindEntityType(typeof(WithAnnotations))!.GetDiscriminatorValue()); + Assert.Equal((int)RawEnum.B, snapshotModel.FindEntityType(typeof(Derived))!.GetDiscriminatorValue()); } [Fact] @@ -143,7 +143,7 @@ public void Migrations_compile() { Table = "T1", Columns = ["Id", "C2", "C3"], - Values = new object[,] { { 1, null, -1 } } + Values = new object[,] { { 1, null!, -1 } } } ], []); @@ -279,13 +279,13 @@ protected override void BuildTargetModel(ModelBuilder modelBuilder) var assembly = build.BuildInMemory(); - var migrationType = assembly.GetType("MyNamespace.MyMigration", throwOnError: true, ignoreCase: false); + var migrationType = assembly.GetType("MyNamespace.MyMigration", throwOnError: true, ignoreCase: false)!; var contextTypeAttribute = migrationType.GetCustomAttribute(); Assert.NotNull(contextTypeAttribute); Assert.Equal(typeof(MyContext), contextTypeAttribute.ContextType); - var migration = (Migration)Activator.CreateInstance(migrationType); + var migration = (Migration)Activator.CreateInstance(migrationType)!; Assert.Equal("20150511161616_MyMigration", migration.GetId()); @@ -323,7 +323,7 @@ public void Namespaces_imported_for_insert_data() { Table = "MyTable", Columns = ["Id", "MyColumn"], - Values = new object[,] { { 1, null }, { 2, RegexOptions.Multiline } } + Values = new object[,] { { 1, null! }, { 2, RegexOptions.Multiline } } } ], []); diff --git a/test/EFCore.Design.Tests/Migrations/Design/CSharpMigrationsGeneratorTestBase.cs b/test/EFCore.Design.Tests/Migrations/Design/CSharpMigrationsGeneratorTestBase.cs index 8878d379cea..bf8bdaf9155 100644 --- a/test/EFCore.Design.Tests/Migrations/Design/CSharpMigrationsGeneratorTestBase.cs +++ b/test/EFCore.Design.Tests/Migrations/Design/CSharpMigrationsGeneratorTestBase.cs @@ -84,25 +84,25 @@ protected virtual IModel BuildModelFromSnapshotSource(string code) } var assembly = build.BuildInMemory(); - var snapshotType = assembly.GetType("RootNamespace.Snapshot"); + var snapshotType = assembly.GetType("RootNamespace.Snapshot")!; var buildModelMethod = snapshotType.GetMethod( "BuildModel", BindingFlags.Instance | BindingFlags.NonPublic, null, [typeof(ModelBuilder)], - null); + null)!; var builder = new ModelBuilder(); builder.Model.RemoveAnnotation(CoreAnnotationNames.ProductVersion); buildModelMethod.Invoke( - Activator.CreateInstance(snapshotType), + Activator.CreateInstance(snapshotType)!, [builder]); var services = TestHelpers.CreateContextServices(GetServices()); - var processor = new SnapshotModelProcessor(new TestOperationReporter(), services.GetService()); - return processor.Process(builder.Model); + var processor = new SnapshotModelProcessor(new TestOperationReporter(), services.GetRequiredService()); + return processor.Process(builder.Model)!; } protected virtual MigrationsModelDiffer CreateModelDiffer(DbContextOptions options) @@ -122,13 +122,13 @@ protected virtual ModelSnapshot CompileModelSnapshot(string code, string modelSn var assembly = build.BuildInMemory(); - var snapshotType = assembly.GetType(modelSnapshotTypeName, throwOnError: true, ignoreCase: false); + var snapshotType = assembly.GetType(modelSnapshotTypeName, throwOnError: true, ignoreCase: false)!; var contextTypeAttribute = snapshotType.GetCustomAttribute(); Assert.NotNull(contextTypeAttribute); Assert.Equal(contextType, contextTypeAttribute.ContextType); - return (ModelSnapshot)Activator.CreateInstance(snapshotType); + return (ModelSnapshot)Activator.CreateInstance(snapshotType)!; } protected class EntityWithAutoincrement diff --git a/test/EFCore.Design.Tests/Migrations/Design/MigrationScaffolderTest.cs b/test/EFCore.Design.Tests/Migrations/Design/MigrationScaffolderTest.cs index 342b9451b2e..0ec8c08b9e4 100644 --- a/test/EFCore.Design.Tests/Migrations/Design/MigrationScaffolderTest.cs +++ b/test/EFCore.Design.Tests/Migrations/Design/MigrationScaffolderTest.cs @@ -161,19 +161,19 @@ public virtual LockReleaseBehavior LockReleaseBehavior => LockReleaseBehavior.Explicit; public string GetBeginIfExistsScript(string migrationId) - => null; + => null!; public string GetBeginIfNotExistsScript(string migrationId) - => null; + => null!; public string GetCreateScript() - => null; + => null!; public string GetCreateIfNotExistsScript() - => null; + => null!; public string GetEndIfScript() - => null; + => null!; public bool Exists() => false; @@ -182,16 +182,16 @@ public Task ExistsAsync(CancellationToken cancellationToken) => Task.FromResult(false); public IReadOnlyList GetAppliedMigrations() - => null; + => null!; public Task> GetAppliedMigrationsAsync(CancellationToken cancellationToken) - => Task.FromResult>(null); + => Task.FromResult>(null!); public string GetDeleteScript(string migrationId) - => null; + => null!; public string GetInsertScript(HistoryRow row) - => null; + => null!; public void Create() => throw new NotImplementedException(); diff --git a/test/EFCore.Design.Tests/Migrations/Design/MigrationsBundleTest.cs b/test/EFCore.Design.Tests/Migrations/Design/MigrationsBundleTest.cs index 96d291ac743..d07414a6583 100644 --- a/test/EFCore.Design.Tests/Migrations/Design/MigrationsBundleTest.cs +++ b/test/EFCore.Design.Tests/Migrations/Design/MigrationsBundleTest.cs @@ -89,12 +89,13 @@ private static IEnumerable GetCommands(CommandLineApplic private static string GetFullName(CommandLineApplication command) { var names = new Stack(); + CommandLineApplication? currentCommand = command; - while (command != null) + while (currentCommand != null) { - names.Push(command.Name); + names.Push(currentCommand.Name!); - command = command.Parent; + currentCommand = currentCommand.Parent; } return string.Join(" ", names); diff --git a/test/EFCore.Design.Tests/Migrations/Design/SnapshotModelProcessorTest.cs b/test/EFCore.Design.Tests/Migrations/Design/SnapshotModelProcessorTest.cs index eef8266c151..752416629eb 100644 --- a/test/EFCore.Design.Tests/Migrations/Design/SnapshotModelProcessorTest.cs +++ b/test/EFCore.Design.Tests/Migrations/Design/SnapshotModelProcessorTest.cs @@ -26,8 +26,8 @@ public void Updates_provider_annotations_on_model() builder.Entity().Property(e => e.BlogId); var foreignKey = builder.Entity().HasMany(e => e.Posts).WithOne(e => e.Blog).HasForeignKey(e => e.BlogId).Metadata; - var nav1 = foreignKey.DependentToPrincipal; - var nav2 = foreignKey.PrincipalToDependent; + var nav1 = foreignKey.DependentToPrincipal!; + var nav2 = foreignKey.PrincipalToDependent!; var index = builder.Entity().HasIndex(e => e.BlogId).Metadata; @@ -91,7 +91,7 @@ public void Warns_for_conflicting_annotations() Assert.Equal(RelationalStrings.MultipleAnnotationConflict("DefaultSchema"), message); Assert.Equal(2, model.GetAnnotations().Count()); - var actual = (string)model["Relational:DefaultSchema"]; + var actual = (string)model["Relational:DefaultSchema"]!; Assert.True(actual is "Value1" or "Value2"); } @@ -114,7 +114,7 @@ public void Warns_for_conflicting_annotations_one_relational() Assert.Equal(RelationalStrings.MultipleAnnotationConflict("DefaultSchema"), message); Assert.Equal(2, model.GetAnnotations().Count()); - var actual = (string)model["Relational:DefaultSchema"]; + var actual = (string)model["Relational:DefaultSchema"]!; Assert.True(actual is "Value1" or "Value2"); } @@ -135,7 +135,7 @@ public void Does_not_warn_for_duplicate_non_conflicting_annotations() Assert.Empty(reporter.Messages); Assert.Equal(2, model.GetAnnotations().Count()); - Assert.Equal("Value", (string)model["Relational:DefaultSchema"]); + Assert.Equal("Value", (string)model["Relational:DefaultSchema"]!); } [Fact] @@ -154,7 +154,7 @@ public void Does_not_process_non_v1_models() Assert.Empty(reporter.Messages); Assert.Equal(2, model.GetAnnotations().Count()); - Assert.Equal("Value", (string)model["Unicorn:DefaultSchema"]); + Assert.Equal("Value", (string)model["Unicorn:DefaultSchema"]!); } [Fact] @@ -179,7 +179,7 @@ public void Sets_owned_type_keys() Assert.Empty(reporter.Messages); Assert.Equal( nameof(BlogDetails.BlogId), - model.FindEntityType(typeof(Blog)).FindNavigation(nameof(Blog.Details)).TargetEntityType.FindPrimaryKey().Properties + model.FindEntityType(typeof(Blog))!.FindNavigation(nameof(Blog.Details))!.TargetEntityType.FindPrimaryKey()!.Properties .Single() .Name); } @@ -321,13 +321,13 @@ public void Updates_property_bag_complex_property_nullability_for_pre_10_snapsho private static void AssertSameSnapshot(Type snapshotType, DbContext context) { var differ = context.GetService(); - var snapshot = (ModelSnapshot)Activator.CreateInstance(snapshotType); + var snapshot = (ModelSnapshot)Activator.CreateInstance(snapshotType)!; var reporter = new TestOperationReporter(); var modelRuntimeInitializer = SqlServerTestHelpers.Instance.CreateContextServices().GetRequiredService(); var model = PreprocessModel(snapshot); - model = new SnapshotModelProcessor(reporter, modelRuntimeInitializer).Process(model, resetVersion: true); + model = new SnapshotModelProcessor(reporter, modelRuntimeInitializer).Process(model, resetVersion: true)!; var currentModel = context.GetService().Model; var differences = differ.GetDifferences( @@ -434,7 +434,7 @@ private void AssertAnnotations(IMutableAnnotatable element) #pragma warning restore CS0618 // Type or member is obsolete && a.IndexOf(':') > 0)) { - Assert.Equal("Value", (string)element[annotationName]); + Assert.Equal("Value", (string)element[annotationName]!); } } @@ -453,7 +453,7 @@ public IModel Initialize(IModel model, IDiagnosticsLogger validationLogger = null) + IDiagnosticsLogger? validationLogger = null) => model; public static DummyModelRuntimeInitializer Instance { get; } = new(); @@ -463,21 +463,21 @@ private class Blog { public int Id { get; set; } - public ICollection Posts { get; set; } - public BlogDetails Details { get; set; } + public ICollection Posts { get; set; } = null!; + public BlogDetails Details { get; set; } = null!; } private class Post { public int BlogId { get; set; } - public Blog Blog { get; set; } + public Blog Blog { get; set; } = null!; } private class BlogDetails { public int BlogId { get; set; } - public ICollection Posts { get; set; } + public ICollection Posts { get; set; } = null!; } private class EntityWithComplexProperty @@ -1607,23 +1607,23 @@ namespace Ownership internal class OwningType1 { public int Id { get; set; } - public OwnedType OwnedType1 { get; set; } - public OwnedType OwnedType2 { get; set; } + public OwnedType? OwnedType1 { get; set; } + public OwnedType? OwnedType2 { get; set; } } internal class OwningType2 { public int Id { get; set; } - public OwnedType OwnedType1 { get; set; } - public OwnedType OwnedType2 { get; set; } + public OwnedType? OwnedType1 { get; set; } + public OwnedType? OwnedType2 { get; set; } } [Owned] internal class OwnedType { public bool Exists { get; set; } - public NestedOwnedType NestedOwnedType1 { get; set; } - public NestedOwnedType NestedOwnedType2 { get; set; } + public NestedOwnedType? NestedOwnedType1 { get; set; } + public NestedOwnedType? NestedOwnedType2 { get; set; } } [Owned] diff --git a/test/EFCore.Design.Tests/Query/CSharpToLinqTranslatorTest.cs b/test/EFCore.Design.Tests/Query/CSharpToLinqTranslatorTest.cs index 68fcd27de36..1b765ea5bc2 100644 --- a/test/EFCore.Design.Tests/Query/CSharpToLinqTranslatorTest.cs +++ b/test/EFCore.Design.Tests/Query/CSharpToLinqTranslatorTest.cs @@ -12,8 +12,6 @@ namespace Microsoft.EntityFrameworkCore.Query; // ReSharper disable InconsistentNaming // ReSharper disable RedundantCast -#nullable enable - public class CSharpToLinqTranslatorTest { [Fact] diff --git a/test/EFCore.Design.Tests/Query/LinqToCSharpSyntaxTranslatorTest.cs b/test/EFCore.Design.Tests/Query/LinqToCSharpSyntaxTranslatorTest.cs index a61c0862496..99cb51a0d10 100644 --- a/test/EFCore.Design.Tests/Query/LinqToCSharpSyntaxTranslatorTest.cs +++ b/test/EFCore.Design.Tests/Query/LinqToCSharpSyntaxTranslatorTest.cs @@ -12,8 +12,6 @@ using Xunit.Sdk; using static System.Linq.Expressions.Expression; -#nullable enable - namespace Microsoft.EntityFrameworkCore.Query; public class LinqToCSharpSyntaxTranslatorTest(ITestOutputHelper testOutputHelper) diff --git a/test/EFCore.Design.Tests/Scaffolding/Internal/CSharpDbContextGeneratorTest.cs b/test/EFCore.Design.Tests/Scaffolding/Internal/CSharpDbContextGeneratorTest.cs index a52ed3603da..437ea968d4e 100644 --- a/test/EFCore.Design.Tests/Scaffolding/Internal/CSharpDbContextGeneratorTest.cs +++ b/test/EFCore.Design.Tests/Scaffolding/Internal/CSharpDbContextGeneratorTest.cs @@ -244,7 +244,7 @@ public Task IsRequired_is_generated_for_ref_property_without_nrt() }, model => { - var entityType = model.FindEntityType("TestNamespace.Entity"); + var entityType = model.FindEntityType("TestNamespace.Entity")!; Assert.False(entityType.GetProperty("RequiredString").IsNullable); Assert.True(entityType.GetProperty("NonRequiredString").IsNullable); Assert.False(entityType.GetProperty("RequiredInt").IsNullable); @@ -272,7 +272,7 @@ public Task IsRequired_is_not_generated_for_ref_property_with_nrt() }, model => { - var entityType = model.FindEntityType("TestNamespace.Entity"); + var entityType = model.FindEntityType("TestNamespace.Entity")!; Assert.False(entityType.GetProperty("RequiredString").IsNullable); Assert.True(entityType.GetProperty("NonRequiredString").IsNullable); Assert.False(entityType.GetProperty("RequiredInt").IsNullable); @@ -296,7 +296,7 @@ public Task Comments_use_fluent_api() code.ContextFile.Code), model => Assert.Equal( "An int property", - model.FindEntityType("TestNamespace.Entity").GetProperty("Property").GetComment())); + model.FindEntityType("TestNamespace.Entity")!.GetProperty("Property").GetComment())); [Fact] public Task Entity_comments_use_fluent_api() @@ -310,7 +310,7 @@ public Task Entity_comments_use_fluent_api() code.ContextFile.Code), model => Assert.Equal( "An entity comment", - model.FindEntityType("TestNamespace.Entity").GetComment())); + model.FindEntityType("TestNamespace.Entity")!.GetComment())); [Fact] public Task Views_work() @@ -320,7 +320,7 @@ public Task Views_work() code => Assert.Contains(".ToView(\"Vista\")", code.ContextFile.Code), model => { - var entityType = model.FindEntityType("TestNamespace.Vista"); + var entityType = model.FindEntityType("TestNamespace.Vista")!; Assert.NotNull(entityType.FindAnnotation(RelationalAnnotationNames.ViewDefinitionSql)); Assert.Equal("Vista", entityType.GetViewName()); @@ -387,7 +387,7 @@ public Task ValueGenerated_works() }, model => { - var entity = model.FindEntityType("TestNamespace.Entity"); + var entity = model.FindEntityType("TestNamespace.Entity")!; Assert.Equal(ValueGenerated.OnAdd, entity.GetProperty("ValueGeneratedOnAdd").ValueGenerated); Assert.Equal(ValueGenerated.OnAddOrUpdate, entity.GetProperty("ValueGeneratedOnAddOrUpdate").ValueGenerated); Assert.True(entity.GetProperty("ConcurrencyToken").IsConcurrencyToken); @@ -413,7 +413,7 @@ public Task HasPrecision_works() }, model => { - var entity = model.FindEntityType("TestNamespace.Entity"); + var entity = model.FindEntityType("TestNamespace.Entity")!; Assert.Equal(12, entity.GetProperty("HasPrecision").GetPrecision()); Assert.Null(entity.GetProperty("HasPrecision").GetScale()); Assert.Equal(14, entity.GetProperty("HasPrecisionAndScale").GetPrecision()); @@ -428,7 +428,7 @@ public Task Collation_works() code => Assert.Contains("Property(e => e.UseCollation).UseCollation(\"Some Collation\")", code.ContextFile.Code), model => { - var entity = model.FindEntityType("TestNamespace.Entity"); + var entity = model.FindEntityType("TestNamespace.Entity")!; Assert.Equal("Some Collation", entity.GetProperty("UseCollation").GetCollation()); }); @@ -440,14 +440,14 @@ public Task ComputedColumnSql_works() code => Assert.Contains(".HasComputedColumnSql(\"1 + 2\")", code.ContextFile.Code), model => { - var entity = model.FindEntityType("TestNamespace.Entity"); + var entity = model.FindEntityType("TestNamespace.Entity")!; Assert.Equal("1 + 2", entity.GetProperty("ComputedColumn").GetComputedColumnSql()); }); [Fact] public Task Column_with_default_value_only_uses_default_value() => TestAsync( - serviceProvider => serviceProvider.GetService().Create( + serviceProvider => serviceProvider.GetRequiredService().Create( BuildModelWithColumn("nvarchar(max)", null, "Hot"), new ModelReverseEngineerOptions()), new ModelCodeGenerationOptions(), code => Assert.Contains(".HasDefaultValue(\"Hot\")", code.ContextFile.Code), @@ -461,7 +461,7 @@ public Task Column_with_default_value_only_uses_default_value() [Fact] public Task Column_with_default_value_sql_only_uses_default_value_sql() => TestAsync( - serviceProvider => serviceProvider.GetService().Create( + serviceProvider => serviceProvider.GetRequiredService().Create( BuildModelWithColumn("nvarchar(max)", "('Hot')", null), new ModelReverseEngineerOptions()), new ModelCodeGenerationOptions(), code => Assert.Contains(".HasDefaultValueSql(\"('Hot')\")", code.ContextFile.Code), @@ -475,7 +475,7 @@ public Task Column_with_default_value_sql_only_uses_default_value_sql() [Fact] public Task Column_with_default_value_sql_and_default_value_uses_default_value() => TestAsync( - serviceProvider => serviceProvider.GetService().Create( + serviceProvider => serviceProvider.GetRequiredService().Create( BuildModelWithColumn("nvarchar(max)", "('Hot')", "Hot"), new ModelReverseEngineerOptions()), new ModelCodeGenerationOptions(), code => Assert.Contains(".HasDefaultValue(\"Hot\")", code.ContextFile.Code), @@ -489,7 +489,7 @@ public Task Column_with_default_value_sql_and_default_value_uses_default_value() [Fact] public Task Column_with_default_value_sql_and_default_value_where_value_is_CLR_default_uses_neither() => TestAsync( - serviceProvider => serviceProvider.GetService().Create( + serviceProvider => serviceProvider.GetRequiredService().Create( BuildModelWithColumn("int", "((0))", 0), new ModelReverseEngineerOptions()), new ModelCodeGenerationOptions(), code => Assert.DoesNotContain("HasDefaultValue", code.ContextFile.Code), @@ -516,7 +516,7 @@ public Task IsUnicode_works() }, model => { - var entity = model.FindEntityType("TestNamespace.Entity"); + var entity = model.FindEntityType("TestNamespace.Entity")!; Assert.True(entity.GetProperty("UnicodeColumn").IsUnicode()); Assert.False(entity.GetProperty("NonUnicodeColumn").IsUnicode()); }); @@ -530,7 +530,7 @@ public Task ComputedColumnSql_works_stored() code => Assert.Contains(".HasComputedColumnSql(\"1 + 2\", true)", code.ContextFile.Code), model => { - var entity = model.FindEntityType("TestNamespace.Entity"); + var entity = model.FindEntityType("TestNamespace.Entity")!; Assert.True(entity.GetProperty("ComputedColumn").GetIsStored()); }); @@ -542,8 +542,8 @@ public Task ComputedColumnSql_works_unspecified() code => Assert.Contains(".HasComputedColumnSql()", code.ContextFile.Code), model => { - var entity = model.FindEntityType("TestNamespace.Entity"); - Assert.Empty(entity.GetProperty("ComputedColumn").GetComputedColumnSql()); + var entity = model.FindEntityType("TestNamespace.Entity")!; + Assert.Empty(entity.GetProperty("ComputedColumn").GetComputedColumnSql()!); }); [Fact] @@ -554,7 +554,7 @@ public Task DefaultValue_works_unspecified() code => Assert.Contains(".HasDefaultValue()", code.ContextFile.Code), model => { - var entity = model.FindEntityType("TestNamespace.Entity"); + var entity = model.FindEntityType("TestNamespace.Entity")!; Assert.Equal(DBNull.Value, entity.GetProperty("DefaultedColumn").GetDefaultValue()); }); @@ -566,8 +566,8 @@ public Task DefaultValueSql_works_unspecified() code => Assert.Contains(".HasDefaultValueSql()", code.ContextFile.Code), model => { - var entity = model.FindEntityType("TestNamespace.Entity"); - Assert.Empty(entity.GetProperty("DefaultedColumn").GetDefaultValueSql()); + var entity = model.FindEntityType("TestNamespace.Entity")!; + Assert.Empty(entity.GetProperty("DefaultedColumn").GetDefaultValueSql()!); }); [Fact] @@ -637,7 +637,7 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) """, code.ContextFile), model => - Assert.Equal(2, model.FindEntityType("TestNamespace.EntityWithIndexes").GetIndexes().Count())); + Assert.Equal(2, model.FindEntityType("TestNamespace.EntityWithIndexes")!.GetIndexes().Count())); [Fact] public Task Entity_with_indexes_and_use_data_annotations_true_generates_fluent_API_only_for_indexes_with_annotations() @@ -702,7 +702,7 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) """, code.ContextFile), model => - Assert.Equal(2, model.FindEntityType("TestNamespace.EntityWithIndexes").GetIndexes().Count())); + Assert.Equal(2, model.FindEntityType("TestNamespace.EntityWithIndexes")!.GetIndexes().Count())); [Fact] public Task Indexes_with_descending() @@ -927,7 +927,7 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) """, code.ContextFile), model => - Assert.Equal("date", model.FindEntityType("TestNamespace.Employee").GetProperty("HireDate").GetConfiguredColumnType())); + Assert.Equal("date", model.FindEntityType("TestNamespace.Employee")!.GetProperty("HireDate").GetConfiguredColumnType())); [Fact] public Task Is_fixed_length_annotation_should_be_scaffolded_without_optional_parameter() @@ -943,7 +943,7 @@ public Task Is_fixed_length_annotation_should_be_scaffolded_without_optional_par new ModelCodeGenerationOptions { UseDataAnnotations = false }, code => Assert.Contains(".IsFixedLength()", code.ContextFile.Code), model => - Assert.True(model.FindEntityType("TestNamespace.Employee").GetProperty("Name").IsFixedLength())); + Assert.True(model.FindEntityType("TestNamespace.Employee")!.GetProperty("Name").IsFixedLength())); [Fact] public Task Global_namespace_works() @@ -1299,7 +1299,7 @@ public Task ColumnOrder_is_ignored(bool useDataAnnotations) }, model => { - var entity = model.FindEntityType("TestNamespace.Entity"); + var entity = model.FindEntityType("TestNamespace.Entity")!; Assert.Null(entity.GetProperty("Property").GetColumnOrder()); }); @@ -1333,7 +1333,7 @@ private static readonly MethodInfo _testFluentApiCallMethodInfo = typeof(TestModelBuilderExtensions).GetRuntimeMethod( nameof(TestModelBuilderExtensions.TestFluentApiCall), [typeof(ModelBuilder)])!; - protected override MethodCallCodeFragment GenerateFluentApi(IModel model, IAnnotation annotation) + protected override MethodCallCodeFragment? GenerateFluentApi(IModel model, IAnnotation annotation) => annotation.Name switch { "Test:TestModelAnnotation" => new MethodCallCodeFragment(_testFluentApiCallMethodInfo), @@ -1345,11 +1345,11 @@ private class TestCodeGeneratorPlugin : ProviderCodeGeneratorPlugin { private static readonly MethodInfo _setProviderOptionMethodInfo = typeof(TestCodeGeneratorPlugin).GetRuntimeMethod( - nameof(SetProviderOption), [typeof(SqlServerDbContextOptionsBuilder)]); + nameof(SetProviderOption), [typeof(SqlServerDbContextOptionsBuilder)])!; private static readonly MethodInfo _setContextOptionMethodInfo = typeof(TestCodeGeneratorPlugin).GetRuntimeMethod( - nameof(SetContextOption), [typeof(DbContextOptionsBuilder)]); + nameof(SetContextOption), [typeof(DbContextOptionsBuilder)])!; public override MethodCallCodeFragment GenerateProviderOptions() => new(_setProviderOptionMethodInfo); diff --git a/test/EFCore.Design.Tests/Scaffolding/Internal/CSharpEntityTypeGeneratorTest.cs b/test/EFCore.Design.Tests/Scaffolding/Internal/CSharpEntityTypeGeneratorTest.cs index 4c407e688d3..1eb01211157 100644 --- a/test/EFCore.Design.Tests/Scaffolding/Internal/CSharpEntityTypeGeneratorTest.cs +++ b/test/EFCore.Design.Tests/Scaffolding/Internal/CSharpEntityTypeGeneratorTest.cs @@ -74,7 +74,7 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) }, model => { - var entityType = model.FindEntityType("TestNamespace.Vista"); + var entityType = model.FindEntityType("TestNamespace.Vista")!; Assert.Null(entityType.FindPrimaryKey()); }); @@ -111,7 +111,7 @@ public partial class Vista code.AdditionalFiles.Single(f => f.Path == "Vista.cs")), model => { - var entityType = model.FindEntityType("TestNamespace.Vista"); + var entityType = model.FindEntityType("TestNamespace.Vista")!; Assert.Equal("Vistas", entityType.GetTableName()); Assert.Null(entityType.GetSchema()); }); @@ -151,7 +151,7 @@ public partial class Vista code.AdditionalFiles.Single(f => f.Path == "Vista.cs")), model => { - var entityType = model.FindEntityType("TestNamespace.Vista"); + var entityType = model.FindEntityType("TestNamespace.Vista")!; Assert.Equal("Vista", entityType.GetTableName()); Assert.Null(entityType.GetSchema()); // Takes through model default schema }); @@ -192,7 +192,7 @@ public partial class Vista code.AdditionalFiles.Single(f => f.Path == "Vista.cs")), model => { - var entityType = model.FindEntityType("TestNamespace.Vista"); + var entityType = model.FindEntityType("TestNamespace.Vista")!; Assert.Equal("Vista", entityType.GetTableName()); Assert.Equal("custom", entityType.GetSchema()); }); @@ -220,7 +220,7 @@ public partial class Vista code.AdditionalFiles.Single(f => f.Path == "Vista.cs")), model => { - var entityType = model.FindEntityType("TestNamespace.Vista"); + var entityType = model.FindEntityType("TestNamespace.Vista")!; Assert.Equal("Vistas", entityType.GetViewName()); Assert.Null(entityType.GetTableName()); Assert.Equal("dbo", entityType.GetViewSchema()); @@ -275,7 +275,7 @@ public partial class EntityWithIndexes code.AdditionalFiles.Single(f => f.Path == "EntityWithIndexes.cs")), model => { - var entityType = model.FindEntityType("TestNamespace.EntityWithIndexes"); + var entityType = model.FindEntityType("TestNamespace.EntityWithIndexes")!; var indexes = entityType.GetIndexes(); Assert.Collection( indexes, @@ -327,7 +327,7 @@ public partial class EntityWithAscendingDescendingIndexes code.AdditionalFiles.Single(f => f.Path == "EntityWithAscendingDescendingIndexes.cs")), model => { - var entityType = model.FindEntityType("TestNamespace.EntityWithAscendingDescendingIndexes"); + var entityType = model.FindEntityType("TestNamespace.EntityWithAscendingDescendingIndexes")!; var indexes = entityType.GetIndexes(); Assert.Collection( indexes, @@ -435,7 +435,7 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) code.ContextFile); }, model => - Assert.Equal(2, model.FindEntityType("TestNamespace.EntityWithIndexes").GetIndexes().Count())); + Assert.Equal(2, model.FindEntityType("TestNamespace.EntityWithIndexes")!.GetIndexes().Count())); [Fact] public Task KeyAttribute_is_generated_for_single_property_and_no_fluent_api() @@ -505,7 +505,7 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) code.ContextFile); }, model => - Assert.Equal("PrimaryKey", model.FindEntityType("TestNamespace.Entity").FindPrimaryKey().Properties[0].Name)); + Assert.Equal("PrimaryKey", model.FindEntityType("TestNamespace.Entity")!.FindPrimaryKey()!.Properties[0].Name)); [Fact] public Task KeyAttribute_is_generated_on_multiple_properties_but_and_uses_PrimaryKeyAttribute_for_composite_key() @@ -581,8 +581,8 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) }, model => { - var postType = model.FindEntityType("TestNamespace.Post"); - Assert.Equal(["Key", "Serial"], postType.FindPrimaryKey().Properties.Select(p => p.Name)); + var postType = model.FindEntityType("TestNamespace.Post")!; + Assert.Equal(["Key", "Serial"], postType.FindPrimaryKey()!.Properties.Select(p => p.Name)); }); [Fact] @@ -628,7 +628,7 @@ public partial class Entity code.AdditionalFiles.Single(f => f.Path == "Entity.cs")), model => { - var entityType = model.FindEntityType("TestNamespace.Entity"); + var entityType = model.FindEntityType("TestNamespace.Entity")!; Assert.False(entityType.GetProperty("RequiredString").IsNullable); Assert.True(entityType.GetProperty("NonRequiredString").IsNullable); Assert.False(entityType.GetProperty("RequiredInt").IsNullable); @@ -677,7 +677,7 @@ public partial class Entity code.AdditionalFiles.Single(f => f.Path == "Entity.cs")), model => { - var entityType = model.FindEntityType("TestNamespace.Entity"); + var entityType = model.FindEntityType("TestNamespace.Entity")!; Assert.False(entityType.GetProperty("RequiredString").IsNullable); Assert.True(entityType.GetProperty("NonRequiredString").IsNullable); Assert.False(entityType.GetProperty("RequiredInt").IsNullable); @@ -748,7 +748,7 @@ public partial class Entity code.AdditionalFiles.Single(f => f.Path == "Entity.cs")), model => { - var entityType = model.FindEntityType("TestNamespace.Entity"); + var entityType = model.FindEntityType("TestNamespace.Entity")!; Assert.False(entityType.GetProperty("RequiredReferenceNavigationId").IsNullable); Assert.True(entityType.GetProperty("OptionalReferenceNavigationId").IsNullable); @@ -829,7 +829,7 @@ public partial class Entity code.AdditionalFiles.Single(f => f.Path == "Entity.cs")), model => { - var entityType = model.FindEntityType("TestNamespace.Entity"); + var entityType = model.FindEntityType("TestNamespace.Entity")!; Assert.True(entityType.FindNavigation("RequiredNavigationWithReferenceForeignKey")!.ForeignKey.IsRequired); Assert.False(entityType.FindNavigation("OptionalNavigationWithReferenceForeignKey")!.ForeignKey.IsRequired); @@ -910,7 +910,7 @@ public partial class Entity }, model => { - var entityType = model.FindEntityType("TestNamespace.Entity"); + var entityType = model.FindEntityType("TestNamespace.Entity")!; Assert.False(entityType.GetProperty("RequiredNavigationWithReferenceForeignKeyId").IsNullable); Assert.True(entityType.GetProperty("OptionalNavigationWithReferenceForeignKeyId").IsNullable); @@ -953,7 +953,7 @@ public partial class Entity """, code.AdditionalFiles.Single(f => f.Path == "Entity.cs")), model => - Assert.False(model.FindEntityType("TestNamespace.Entity").GetProperty("RequiredString").IsNullable)); + Assert.False(model.FindEntityType("TestNamespace.Entity")!.GetProperty("RequiredString").IsNullable)); [Fact] public Task ColumnAttribute_is_generated_for_property() @@ -1043,7 +1043,7 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) }, model => { - var entitType = model.FindEntityType("TestNamespace.Entity"); + var entitType = model.FindEntityType("TestNamespace.Entity")!; Assert.Equal("propertyA", entitType.GetProperty("A").GetColumnName()); Assert.Equal("nchar(10)", entitType.GetProperty("B").GetColumnType()); Assert.Equal("random", entitType.GetProperty("C").GetColumnName()); @@ -1088,7 +1088,7 @@ public partial class Entity code.AdditionalFiles.Single(f => f.Path == "Entity.cs")), model => { - var entitType = model.FindEntityType("TestNamespace.Entity"); + var entitType = model.FindEntityType("TestNamespace.Entity")!; Assert.Equal(34, entitType.GetProperty("A").GetMaxLength()); Assert.Equal(10, entitType.GetProperty("B").GetMaxLength()); }); @@ -1137,7 +1137,7 @@ public partial class Entity code.AdditionalFiles.Single(f => f.Path == "Entity.cs")), model => { - var entitType = model.FindEntityType("TestNamespace.Entity"); + var entitType = model.FindEntityType("TestNamespace.Entity")!; Assert.True(entitType.GetProperty("A").IsUnicode()); Assert.False(entitType.GetProperty("B").IsUnicode()); Assert.Null(entitType.GetProperty("C").IsUnicode()); @@ -1189,7 +1189,7 @@ public partial class Entity code.AdditionalFiles.Single(f => f.Path == "Entity.cs")), model => { - var entitType = model.FindEntityType("TestNamespace.Entity"); + var entitType = model.FindEntityType("TestNamespace.Entity")!; Assert.Equal(10, entitType.GetProperty("A").GetPrecision()); Assert.Equal(14, entitType.GetProperty("B").GetPrecision()); Assert.Equal(3, entitType.GetProperty("B").GetScale()); @@ -1396,12 +1396,12 @@ public partial class Person }, model => { - var postType = model.FindEntityType("TestNamespace.Post"); - var authorNavigation = postType.FindNavigation("Author"); + var postType = model.FindEntityType("TestNamespace.Post")!; + var authorNavigation = postType.FindNavigation("Author")!; Assert.True(authorNavigation.IsOnDependent); Assert.Equal("TestNamespace.Person", authorNavigation.ForeignKey.PrincipalEntityType.Name); - var contributionsNav = postType.FindNavigation("Contributions"); + var contributionsNav = postType.FindNavigation("Contributions")!; Assert.False(contributionsNav.IsOnDependent); Assert.Equal("TestNamespace.Contribution", contributionsNav.ForeignKey.DeclaringEntityType.Name); }); @@ -1494,8 +1494,8 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) }, model => { - var postType = model.FindEntityType("TestNamespace.Post"); - var blogNavigation = postType.FindNavigation("BlogNavigation"); + var postType = model.FindEntityType("TestNamespace.Post")!; + var blogNavigation = postType.FindNavigation("BlogNavigation")!; Assert.Equal("TestNamespace.Blog", blogNavigation.ForeignKey.PrincipalEntityType.Name); Assert.Equal(["BlogId1", "BlogId2"], blogNavigation.ForeignKey.Properties.Select(p => p.Name)); }); @@ -1597,8 +1597,8 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) }, model => { - var postType = model.FindEntityType("TestNamespace.Post"); - var blogNavigation = postType.FindNavigation("BlogNavigation"); + var postType = model.FindEntityType("TestNamespace.Post")!; + var blogNavigation = postType.FindNavigation("BlogNavigation")!; Assert.Equal("TestNamespace.Blog", blogNavigation.ForeignKey.PrincipalEntityType.Name); Assert.Equal(["BlogId1", "BlogId2"], blogNavigation.ForeignKey.Properties.Select(p => p.Name)); Assert.Equal(["Id1", "Id2"], blogNavigation.ForeignKey.PrincipalKey.Properties.Select(p => p.Name)); @@ -1721,8 +1721,8 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) }, model => { - var carType = model.FindEntityType("TestNamespace.Car"); - var colorNavigation = carType.FindNavigation("Color"); + var carType = model.FindEntityType("TestNamespace.Car")!; + var colorNavigation = carType.FindNavigation("Color")!; Assert.Equal("TestNamespace.Color", colorNavigation.ForeignKey.PrincipalEntityType.Name); Assert.Equal(["ColorCode"], colorNavigation.ForeignKey.Properties.Select(p => p.Name)); Assert.Equal(["ColorCode"], colorNavigation.ForeignKey.PrincipalKey.Properties.Select(p => p.Name)); @@ -1815,9 +1815,9 @@ public partial class Post }, model => { - var post = model.FindEntityType("TestNamespace.Post"); + var post = model.FindEntityType("TestNamespace.Post")!; var foreignKey = Assert.Single(post.GetForeignKeys()); - Assert.Equal("Blog", foreignKey.DependentToPrincipal.Name); + Assert.Equal("Blog", foreignKey.DependentToPrincipal!.Name); Assert.Null(foreignKey.PrincipalToDependent); }); @@ -1861,13 +1861,13 @@ public partial class Post code.AdditionalFiles.Single(f => f.Path == "Post.cs")), model => { - var postType = model.FindEntityType("TestNamespace.Post"); - var blogNavigation = postType.FindNavigation("Blog"); + var postType = model.FindEntityType("TestNamespace.Post")!; + var blogNavigation = postType.FindNavigation("Blog")!; var foreignKeyProperty = Assert.Single(blogNavigation.ForeignKey.Properties); Assert.Equal("BlogId", foreignKeyProperty.Name); - var inverseNavigation = blogNavigation.Inverse; + var inverseNavigation = blogNavigation.Inverse!; Assert.Equal("TestNamespace.Blog", inverseNavigation.DeclaringEntityType.Name); Assert.Equal("Posts", inverseNavigation.Name); }); @@ -1912,13 +1912,13 @@ public partial class Post code.AdditionalFiles.Single(f => f.Path == "Post.cs")), model => { - var postType = model.FindEntityType("TestNamespace.Post"); - var blogNavigation = postType.FindNavigation("BlogNavigation"); + var postType = model.FindEntityType("TestNamespace.Post")!; + var blogNavigation = postType.FindNavigation("BlogNavigation")!; var foreignKeyProperty = Assert.Single(blogNavigation.ForeignKey.Properties); Assert.Equal("Blog", foreignKeyProperty.Name); - var inverseNavigation = blogNavigation.Inverse; + var inverseNavigation = blogNavigation.Inverse!; Assert.Equal("TestNamespace.Blog", inverseNavigation.DeclaringEntityType.Name); Assert.Equal("Posts", inverseNavigation.Name); }); @@ -1970,23 +1970,23 @@ public partial class Post code.AdditionalFiles.Single(f => f.Path == "Post.cs")), model => { - var postType = model.FindEntityType("TestNamespace.Post"); + var postType = model.FindEntityType("TestNamespace.Post")!; - var blogNavigation = postType.FindNavigation("Blog"); + var blogNavigation = postType.FindNavigation("Blog")!; var foreignKeyProperty = Assert.Single(blogNavigation.ForeignKey.Properties); Assert.Equal("BlogId", foreignKeyProperty.Name); - var inverseNavigation = blogNavigation.Inverse; + var inverseNavigation = blogNavigation.Inverse!; Assert.Equal("TestNamespace.Blog", inverseNavigation.DeclaringEntityType.Name); Assert.Equal("Posts", inverseNavigation.Name); - var originalBlogNavigation = postType.FindNavigation("OriginalBlog"); + var originalBlogNavigation = postType.FindNavigation("OriginalBlog")!; var originalForeignKeyProperty = Assert.Single(originalBlogNavigation.ForeignKey.Properties); Assert.Equal("OriginalBlogId", originalForeignKeyProperty.Name); - var originalInverseNavigation = originalBlogNavigation.Inverse; + var originalInverseNavigation = originalBlogNavigation.Inverse!; Assert.Equal("TestNamespace.Blog", originalInverseNavigation.DeclaringEntityType.Name); Assert.Equal("OriginalPosts", originalInverseNavigation.Name); }); @@ -2028,8 +2028,8 @@ public partial class Post code.AdditionalFiles.Single(f => f.Path == "Post.cs")), model => { - var postType = model.FindEntityType("TestNamespace.Post"); - var blogNavigation = postType.FindNavigation("Blog"); + var postType = model.FindEntityType("TestNamespace.Post")!; + var blogNavigation = postType.FindNavigation("Blog")!; var foreignKeyProperty = Assert.Single(blogNavigation.ForeignKey.Properties); Assert.Equal("BlogId", foreignKeyProperty.Name); @@ -2288,12 +2288,12 @@ public partial class Post }, model => { - var blogType = model.FindEntityType("TestNamespace.Blog"); + var blogType = model.FindEntityType("TestNamespace.Blog")!; Assert.Empty(blogType.GetNavigations()); var postsNavigation = Assert.Single(blogType.GetSkipNavigations()); Assert.Equal("Posts", postsNavigation.Name); - var postType = model.FindEntityType("TestNamespace.Post"); + var postType = model.FindEntityType("TestNamespace.Post")!; Assert.Empty(postType.GetNavigations()); var blogsNavigation = Assert.Single(postType.GetSkipNavigations()); Assert.Equal("Blogs", blogsNavigation.Name); @@ -2415,12 +2415,12 @@ public partial class Post }, model => { - var blogType = model.FindEntityType("TestNamespace.Blog"); + var blogType = model.FindEntityType("TestNamespace.Blog")!; Assert.Empty(blogType.GetNavigations()); var postsNavigation = Assert.Single(blogType.GetSkipNavigations()); Assert.Equal("Posts", postsNavigation.Name); - var postType = model.FindEntityType("TestNamespace.Post"); + var postType = model.FindEntityType("TestNamespace.Post")!; Assert.Empty(postType.GetNavigations()); var blogsNavigation = Assert.Single(postType.GetSkipNavigations()); Assert.Equal("Blogs", blogsNavigation.Name); @@ -2554,12 +2554,12 @@ public partial class Post }, model => { - var blogType = model.FindEntityType("TestNamespace.Blog"); + var blogType = model.FindEntityType("TestNamespace.Blog")!; Assert.Empty(blogType.GetNavigations()); var postsNavigation = Assert.Single(blogType.GetSkipNavigations()); Assert.Equal("Posts", postsNavigation.Name); - var postType = model.FindEntityType("TestNamespace.Post"); + var postType = model.FindEntityType("TestNamespace.Post")!; Assert.Empty(postType.GetNavigations()); var blogsNavigation = Assert.Single(postType.GetSkipNavigations()); Assert.Equal("Blogs", blogsNavigation.Name); @@ -2701,12 +2701,12 @@ public partial class Post }, model => { - var blogType = model.FindEntityType("TestNamespace.Blog"); + var blogType = model.FindEntityType("TestNamespace.Blog")!; Assert.Empty(blogType.GetNavigations()); var postsNavigation = Assert.Single(blogType.GetSkipNavigations()); Assert.Equal("Posts", postsNavigation.Name); - var postType = model.FindEntityType("TestNamespace.Post"); + var postType = model.FindEntityType("TestNamespace.Post")!; Assert.Empty(postType.GetNavigations()); var blogsNavigation = Assert.Single(postType.GetSkipNavigations()); Assert.Equal("Blogs", blogsNavigation.Name); @@ -3023,7 +3023,7 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) Assert.Equal("Post_Blogs_Source", fk1.GetConstraintName()); var property = Assert.Single(fk1.Properties); Assert.Equal("PostId", property.Name); - Assert.Equal("Post_Id", property.GetColumnName(StoreObjectIdentifier.Table(t1.GetTableName()))); + Assert.Equal("Post_Id", property.GetColumnName(StoreObjectIdentifier.Table(t1.GetTableName()!))); Assert.Equal("TestNamespace.Post", fk1.PrincipalEntityType.Name); Assert.Equal(DeleteBehavior.Cascade, fk1.DeleteBehavior); }, @@ -3032,7 +3032,7 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) Assert.Equal("Post_Blogs_Target", fk2.GetConstraintName()); var property = Assert.Single(fk2.Properties); Assert.Equal("BlogId", property.Name); - Assert.Equal("Blog_Id", property.GetColumnName(StoreObjectIdentifier.Table(t1.GetTableName()))); + Assert.Equal("Blog_Id", property.GetColumnName(StoreObjectIdentifier.Table(t1.GetTableName()!))); Assert.Equal("TestNamespace.Blog", fk2.PrincipalEntityType.Name); Assert.Equal(DeleteBehavior.Cascade, fk2.DeleteBehavior); }); @@ -3104,7 +3104,7 @@ public override IEnumerable For(IColumn column, bool designTime) private class TestModelAnnotationCodeGenerator(AnnotationCodeGeneratorDependencies dependencies) : SqlServerAnnotationCodeGenerator(dependencies) { - protected override AttributeCodeFragment GenerateDataAnnotation(IEntityType entityType, IAnnotation annotation) + protected override AttributeCodeFragment? GenerateDataAnnotation(IEntityType entityType, IAnnotation annotation) => annotation.Name switch { "Custom:EntityAnnotation" => new AttributeCodeFragment( @@ -3112,7 +3112,7 @@ protected override AttributeCodeFragment GenerateDataAnnotation(IEntityType enti _ => base.GenerateDataAnnotation(entityType, annotation) }; - protected override AttributeCodeFragment GenerateDataAnnotation(IProperty property, IAnnotation annotation) + protected override AttributeCodeFragment? GenerateDataAnnotation(IProperty property, IAnnotation annotation) => annotation.Name switch { "Custom:PropertyAnnotation" => new AttributeCodeFragment( diff --git a/test/EFCore.Design.Tests/Scaffolding/Internal/HumanizerPluralizerTest.cs b/test/EFCore.Design.Tests/Scaffolding/Internal/HumanizerPluralizerTest.cs index 00ff8195f66..c4efbff5676 100644 --- a/test/EFCore.Design.Tests/Scaffolding/Internal/HumanizerPluralizerTest.cs +++ b/test/EFCore.Design.Tests/Scaffolding/Internal/HumanizerPluralizerTest.cs @@ -8,16 +8,16 @@ namespace Microsoft.EntityFrameworkCore.Scaffolding.Internal; public class HumanizerPluralizerTest { [Theory, InlineData("Unicorn", "Unicorns"), InlineData("Ox", "Oxen"), InlineData(null, null)] - public void Returns_expected_pluralized_name(string word, string inflected) + public void Returns_expected_pluralized_name(string? word, string? inflected) { var pluralizer = new HumanizerPluralizer(); - Assert.Equal(inflected, pluralizer.Pluralize(word)); + Assert.Equal(inflected, pluralizer.Pluralize(word!)); } [Theory, InlineData("Unicorns", "Unicorn"), InlineData("Oxen", "Ox"), InlineData(null, null)] - public void Returns_expected_singularized_name(string word, string inflected) + public void Returns_expected_singularized_name(string? word, string? inflected) { var pluralizer = new HumanizerPluralizer(); - Assert.Equal(inflected, pluralizer.Singularize(word)); + Assert.Equal(inflected, pluralizer.Singularize(word!)); } } diff --git a/test/EFCore.Design.Tests/Scaffolding/Internal/ModelCodeGeneratorTestBase.cs b/test/EFCore.Design.Tests/Scaffolding/Internal/ModelCodeGeneratorTestBase.cs index 734b6f7d64f..401f7caab80 100644 --- a/test/EFCore.Design.Tests/Scaffolding/Internal/ModelCodeGeneratorTestBase.cs +++ b/test/EFCore.Design.Tests/Scaffolding/Internal/ModelCodeGeneratorTestBase.cs @@ -14,7 +14,7 @@ protected Task TestAsync( Action buildModel, ModelCodeGenerationOptions options, Action assertScaffold, - Action assertModel, + Action? assertModel, bool skipBuild = false) { var modelBuilder = SqlServerTestHelpers.Instance.CreateConventionBuilder(addServices: AddModelServices); @@ -34,7 +34,7 @@ protected Task TestAsync( Func buildModel, ModelCodeGenerationOptions options, Action assertScaffold, - Action assertModel, + Action? assertModel, bool skipBuild = false) { var designServices = new ServiceCollection(); @@ -52,7 +52,7 @@ protected async Task TestAsync( IModel model, ModelCodeGenerationOptions options, Action assertScaffold, - Action assertModel, + Action? assertModel, bool skipBuild = false) { var generators = serviceProvider.GetServices(); @@ -93,10 +93,11 @@ protected async Task TestAsync( if (assertModel != null) { var contextNamespace = options.ContextNamespace ?? options.ModelNamespace; - var context = (DbContext)assembly.CreateInstance( - !string.IsNullOrEmpty(contextNamespace) - ? contextNamespace + "." + options.ContextName - : options.ContextName); + var context = Assert.IsAssignableFrom( + assembly.CreateInstance( + !string.IsNullOrEmpty(contextNamespace) + ? contextNamespace + "." + options.ContextName + : options.ContextName)); var compiledModel = context.GetService().Model; assertModel(compiledModel); @@ -104,7 +105,7 @@ protected async Task TestAsync( } } - protected static DatabaseModel BuildModelWithColumn(string storeType, string sql, object expected) + protected static DatabaseModel BuildModelWithColumn(string storeType, string? sql, object? expected) { var dbModel = new DatabaseModel { diff --git a/test/EFCore.Design.Tests/Scaffolding/Internal/ModelCodeGeneratorTestFixture.cs b/test/EFCore.Design.Tests/Scaffolding/Internal/ModelCodeGeneratorTestFixture.cs index 9f6c7752ad8..c9e4e6bef0b 100644 --- a/test/EFCore.Design.Tests/Scaffolding/Internal/ModelCodeGeneratorTestFixture.cs +++ b/test/EFCore.Design.Tests/Scaffolding/Internal/ModelCodeGeneratorTestFixture.cs @@ -11,14 +11,14 @@ public ModelCodeGeneratorTestFixture() Directory.CreateDirectory(templatesDir); using (var input = typeof(ModelCodeGeneratorTestBase).Assembly.GetManifestResourceStream( - "Microsoft.EntityFrameworkCore.Resources.CSharpDbContextGenerator.tt")) + "Microsoft.EntityFrameworkCore.Resources.CSharpDbContextGenerator.tt")!) using (var output = File.Create(Path.Combine(templatesDir, "DbContext.t4"))) { input.CopyTo(output); } using (var input = typeof(ModelCodeGeneratorTestBase).Assembly.GetManifestResourceStream( - "Microsoft.EntityFrameworkCore.Resources.CSharpEntityTypeGenerator.tt")) + "Microsoft.EntityFrameworkCore.Resources.CSharpEntityTypeGenerator.tt")!) using (var output = File.Create(Path.Combine(templatesDir, "EntityType.t4"))) { input.CopyTo(output); diff --git a/test/EFCore.Design.Tests/Scaffolding/Internal/RelationalScaffoldingModelFactoryTest.cs b/test/EFCore.Design.Tests/Scaffolding/Internal/RelationalScaffoldingModelFactoryTest.cs index 7262bf2d7a9..95f90458d78 100644 --- a/test/EFCore.Design.Tests/Scaffolding/Internal/RelationalScaffoldingModelFactoryTest.cs +++ b/test/EFCore.Design.Tests/Scaffolding/Internal/RelationalScaffoldingModelFactoryTest.cs @@ -207,7 +207,7 @@ public void Loads_column_types() }; var entityType = - (EntityType)_factory.Create(info, new ModelReverseEngineerOptions { NoPluralize = true }).FindEntityType("Jobs"); + (EntityType)_factory.Create(info, new ModelReverseEngineerOptions { NoPluralize = true }).FindEntityType("Jobs")!; Assert.Collection( entityType.GetProperties(), @@ -289,7 +289,7 @@ public void Use_database_names_for_columns() var entityType = _factory .Create(info, new ModelReverseEngineerOptions { UseDatabaseNames = true, NoPluralize = true }) - .FindEntityType("NaturalProducts"); + .FindEntityType("NaturalProducts")!; Assert.Collection( entityType.GetProperties(), @@ -338,7 +338,7 @@ public void Do_not_use_database_names_for_columns() }; var entityType = _factory.Create(info, new ModelReverseEngineerOptions { NoPluralize = true }) - .FindEntityType("NaturalProducts"); + .FindEntityType("NaturalProducts")!; Assert.Collection( entityType.GetProperties(), @@ -349,7 +349,7 @@ public void Do_not_use_database_names_for_columns() } [Theory, InlineData("nvarchar(450)", null), InlineData("datetime2(4)", null), InlineData("DateTime2(4)", "DateTime2(4)")] - public void Column_type_annotation(string storeType, string expectedColumnType) + public void Column_type_annotation(string storeType, string? expectedColumnType) { var column = new DatabaseColumn { @@ -377,7 +377,7 @@ public void Column_type_annotation(string storeType, string expectedColumnType) } }; - var property = (Property)_factory.Create(info, new ModelReverseEngineerOptions()).FindEntityType("A").FindProperty("Col"); + var property = (Property)_factory.Create(info, new ModelReverseEngineerOptions()).FindEntityType("A")!.FindProperty("Col")!; Assert.Equal(expectedColumnType, property.GetConfiguredColumnType()); } @@ -425,10 +425,10 @@ public void Column_ordinal_annotation() } }; - var entityTypeA = _factory.Create(info, new ModelReverseEngineerOptions()).FindEntityType("A"); - var property1 = (Property)entityTypeA.FindProperty("Col1"); - var property2 = (Property)entityTypeA.FindProperty("Col2"); - var property3 = (Property)entityTypeA.FindProperty("Col3"); + var entityTypeA = _factory.Create(info, new ModelReverseEngineerOptions()).FindEntityType("A")!; + var property1 = (Property)entityTypeA.FindProperty("Col1")!; + var property2 = (Property)entityTypeA.FindProperty("Col2")!; + var property3 = (Property)entityTypeA.FindProperty("Col3")!; Assert.Equal(0, property1.GetColumnOrder()); Assert.Equal(1, property2.GetColumnOrder()); @@ -436,7 +436,7 @@ public void Column_ordinal_annotation() } [Theory, InlineData("cheese"), InlineData(null)] - public void Unmappable_column_type(string StoreType) + public void Unmappable_column_type(string? StoreType) { var info = new DatabaseModel { @@ -460,7 +460,7 @@ public void Unmappable_column_type(string StoreType) StoreType = StoreType }); - Assert.Single(_factory.Create(info, new ModelReverseEngineerOptions()).FindEntityType("E").GetProperties()); + Assert.Single(_factory.Create(info, new ModelReverseEngineerOptions()).FindEntityType("E")!.GetProperties()); var (level, message) = _reporter.Messages.Single(); Assert.Equal(LogLevel.Warning, level); @@ -492,13 +492,13 @@ public void Primary_key(string[] keyProps, int length) })) { info.Tables[0].Columns.Add(column); - info.Tables[0].PrimaryKey.Columns.Add(column); + info.Tables[0].PrimaryKey!.Columns.Add(column); } var model = (EntityType)_factory.Create(info, new ModelReverseEngineerOptions()).GetEntityTypes().Single(); - Assert.Equal("MyPk", model.FindPrimaryKey().GetName()); - Assert.Equal(keyProps, model.FindPrimaryKey().Properties.Select(p => p.GetColumnName()).ToArray()); + Assert.Equal("MyPk", model.FindPrimaryKey()!.GetName()); + Assert.Equal(keyProps, model.FindPrimaryKey()!.Properties.Select(p => p.GetColumnName()).ToArray()); } [Fact] @@ -796,9 +796,9 @@ public void Foreign_key() new DatabaseModel { Tables = { parentTable, childrenTable } }, new ModelReverseEngineerOptions { NoPluralize = true }); - var parent = (EntityType)model.FindEntityType("Parent"); + var parent = (EntityType)model.FindEntityType("Parent")!; - var children = (EntityType)model.FindEntityType("Children"); + var children = (EntityType)model.FindEntityType("Children")!; Assert.NotEmpty(parent.GetReferencingForeignKeys()); var fk = Assert.Single(children.GetForeignKeys()); @@ -851,9 +851,9 @@ public void Foreign_key_from_keyless_table() var model = _factory.Create(databaseModel, new ModelReverseEngineerOptions()); - var detail = model.FindEntityType("Detail"); + var detail = model.FindEntityType("Detail")!; var foreignKey = Assert.Single(detail.GetForeignKeys()); - Assert.Equal("Master", foreignKey.DependentToPrincipal.Name); + Assert.Equal("Master", foreignKey.DependentToPrincipal!.Name); Assert.Null(foreignKey.PrincipalToDependent); } @@ -907,9 +907,9 @@ public void Foreign_key_to_unique_constraint() new DatabaseModel { Tables = { parentTable, childrenTable } }, new ModelReverseEngineerOptions { NoPluralize = true }); - var parent = (EntityType)model.FindEntityType("Parent"); + var parent = (EntityType)model.FindEntityType("Parent")!; - var children = (EntityType)model.FindEntityType("Children"); + var children = (EntityType)model.FindEntityType("Children")!; Assert.NotEmpty(parent.GetReferencingForeignKeys()); var fk = Assert.Single(children.GetForeignKeys()); @@ -954,7 +954,7 @@ public void Unique_foreign_key() new DatabaseModel { Tables = { parentTable, childrenTable } }, new ModelReverseEngineerOptions { NoPluralize = true }); - var children = (EntityType)model.FindEntityType("Children"); + var children = (EntityType)model.FindEntityType("Children")!; var fk = Assert.Single(children.GetForeignKeys()); Assert.True(fk.IsUnique); @@ -1025,9 +1025,9 @@ public void Composite_foreign_key() new DatabaseModel { Tables = { parentTable, childrenTable } }, new ModelReverseEngineerOptions { NoPluralize = true }); - var parent = (EntityType)model.FindEntityType("Parent"); + var parent = (EntityType)model.FindEntityType("Parent")!; - var children = (EntityType)model.FindEntityType("Children"); + var children = (EntityType)model.FindEntityType("Children")!; Assert.NotEmpty(parent.GetReferencingForeignKeys()); @@ -1075,12 +1075,12 @@ public void It_loads_self_referencing_foreign_key() var model = _factory.Create( new DatabaseModel { Tables = { table } }, new ModelReverseEngineerOptions()); - var list = model.FindEntityType("ItemsList"); + var list = model.FindEntityType("ItemsList")!; Assert.NotEmpty(list.GetReferencingForeignKeys()); Assert.NotEmpty(list.GetForeignKeys()); - var principalKey = list.FindForeignKeys(list.FindProperty("ParentId")).Single().PrincipalKey; + var principalKey = list.FindForeignKeys(list.FindProperty("ParentId")!).Single().PrincipalKey; Assert.Equal("ItemsList", principalKey.DeclaringEntityType.Name); Assert.Equal("Id", principalKey.Properties[0].Name); } @@ -1236,7 +1236,7 @@ public void Unique_nullable_index_unused_by_foreign_key() var model = _factory.Create( new DatabaseModel { Tables = { table } }, - new ModelReverseEngineerOptions { NoPluralize = true }).FindEntityType("Friends"); + new ModelReverseEngineerOptions { NoPluralize = true }).FindEntityType("Friends")!; var buddyIdProperty = model.FindProperty("BuddyId"); Assert.NotNull(buddyIdProperty); @@ -1289,7 +1289,7 @@ public void Unique_nullable_index_used_by_foreign_key() var model = _factory.Create( new DatabaseModel { Tables = { table } }, - new ModelReverseEngineerOptions { NoPluralize = true }).FindEntityType("Friends"); + new ModelReverseEngineerOptions { NoPluralize = true }).FindEntityType("Friends")!; var buddyIdProperty = model.FindProperty("BuddyId"); Assert.NotNull(buddyIdProperty); @@ -1378,8 +1378,8 @@ public void Unique_index_composite_foreign_key() var model = _factory.Create( new DatabaseModel { Tables = { parentTable, childrenTable } }, new ModelReverseEngineerOptions { NoPluralize = true }); - var parent = model.FindEntityType("Parent"); - var children = model.FindEntityType("Children"); + var parent = model.FindEntityType("Parent")!; + var children = model.FindEntityType("Children")!; var fk = Assert.Single(children.GetForeignKeys()); @@ -1887,7 +1887,7 @@ public void Not_null_bool_column_with_unparsed_default_value_is_made_nullable() var model = _factory.Create(dbModel, new ModelReverseEngineerOptions()); - var columns = model.FindEntityType("Table").GetProperties().ToList(); + var columns = model.FindEntityType("Table")!.GetProperties().ToList(); Assert.Equal(typeof(bool), columns.First(c => c.Name == "NonNullBoolWithoutDefault").ClrType); Assert.False(columns.First(c => c.Name == "NonNullBoolWithoutDefault").IsNullable); @@ -1980,7 +1980,7 @@ public void Nullable_column_with_default_value_sql_does_not_generate_warning() var model = _factory.Create(dbModel, new ModelReverseEngineerOptions()); - var columns = model.FindEntityType("Table").GetProperties().ToList(); + var columns = model.FindEntityType("Table")!.GetProperties().ToList(); Assert.Equal(typeof(bool?), columns.First(c => c.Name == "NullBoolWithDefault").ClrType); Assert.True(columns.First(c => c.Name == "NullBoolWithDefault").IsNullable); @@ -2114,12 +2114,12 @@ public void Correct_arguments_to_scaffolding_typemapper() var model = _factory.Create(dbModel, new ModelReverseEngineerOptions()); - Assert.Null(model.FindEntityType("Principal").FindProperty("PrimaryKey").GetConfiguredColumnType()); - Assert.Null(model.FindEntityType("Principal").FindProperty("AlternateKey").GetConfiguredColumnType()); - Assert.Null(model.FindEntityType("Principal").FindProperty("Index").GetConfiguredColumnType()); - Assert.Null(model.FindEntityType("Principal").FindProperty("Rowversion").GetConfiguredColumnType()); - Assert.Equal(typeof(Guid), model.FindEntityType("Principal").FindProperty("ClrType").ClrType); - Assert.Null(model.FindEntityType("Dependent").FindProperty("BlogAlternateKey").GetConfiguredColumnType()); + Assert.Null(model.FindEntityType("Principal")!.FindProperty("PrimaryKey")!.GetConfiguredColumnType()); + Assert.Null(model.FindEntityType("Principal")!.FindProperty("AlternateKey")!.GetConfiguredColumnType()); + Assert.Null(model.FindEntityType("Principal")!.FindProperty("Index")!.GetConfiguredColumnType()); + Assert.Null(model.FindEntityType("Principal")!.FindProperty("Rowversion")!.GetConfiguredColumnType()); + Assert.Equal(typeof(Guid), model.FindEntityType("Principal")!.FindProperty("ClrType")!.ClrType); + Assert.Null(model.FindEntityType("Dependent")!.FindProperty("BlogAlternateKey")!.GetConfiguredColumnType()); } [Fact] @@ -2148,7 +2148,7 @@ public void Unmapped_column_is_ignored() var model = _factory.Create(dbModel, new ModelReverseEngineerOptions()); - var columns = model.FindEntityType("Table").GetProperties().ToList(); + var columns = model.FindEntityType("Table")!.GetProperties().ToList(); Assert.Single(columns); } @@ -2182,10 +2182,10 @@ public void Column_and_table_comments() var model = _factory.Create(database, new ModelReverseEngineerOptions()); - var table = model.FindEntityType("Table"); + var table = model.FindEntityType("Table")!; Assert.Equal("A table", table.GetComment()); - var column = model.FindEntityType("Table").GetProperty("Column"); + var column = model.FindEntityType("Table")!.GetProperty("Column"); Assert.Equal("An int column", column.GetComment()); } @@ -2226,7 +2226,7 @@ public void Column_collation() var model = _factory.Create(database, new ModelReverseEngineerOptions()); - var column = model.FindEntityType("Table").GetProperty("Column"); + var column = model.FindEntityType("Table")!.GetProperty("Column"); Assert.Equal("SomeColumnCollation", column.GetCollation()); } @@ -2284,18 +2284,18 @@ public void UseDatabaseNames_and_NoPluralize_work_together( Assert.Equal(userTableName, user.Name); Assert.Equal(userTableName, user[ScaffoldingAnnotationNames.DbSetName]); Assert.Equal("id", id.Name); - Assert.Equal(postTableName, foreignKey.PrincipalToDependent.Name); + Assert.Equal(postTableName, foreignKey.PrincipalToDependent!.Name); Assert.Equal("author_id", Assert.Single(foreignKey.Properties).Name); - Assert.Equal("author", foreignKey.DependentToPrincipal.Name); + Assert.Equal("author", foreignKey.DependentToPrincipal!.Name); } else if (useDatabaseNames) { Assert.Equal("user", user.Name); Assert.Equal("users", user[ScaffoldingAnnotationNames.DbSetName]); Assert.Equal("id", id.Name); - Assert.Equal("posts", foreignKey.PrincipalToDependent.Name); + Assert.Equal("posts", foreignKey.PrincipalToDependent!.Name); Assert.Equal("author_id", Assert.Single(foreignKey.Properties).Name); - Assert.Equal("author", foreignKey.DependentToPrincipal.Name); + Assert.Equal("author", foreignKey.DependentToPrincipal!.Name); } else if (noPluralize) { @@ -2304,18 +2304,18 @@ public void UseDatabaseNames_and_NoPluralize_work_together( Assert.Equal("Users", user.Name); Assert.Equal("Users", user[ScaffoldingAnnotationNames.DbSetName]); Assert.Equal("Id", id.Name); - Assert.Equal("Posts", foreignKey.PrincipalToDependent.Name); + Assert.Equal("Posts", foreignKey.PrincipalToDependent!.Name); Assert.Equal("AuthorId", Assert.Single(foreignKey.Properties).Name); - Assert.Equal("Author", foreignKey.DependentToPrincipal.Name); + Assert.Equal("Author", foreignKey.DependentToPrincipal!.Name); } else { Assert.Equal("User", user.Name); Assert.Equal("User", user[ScaffoldingAnnotationNames.DbSetName]); Assert.Equal("Id", id.Name); - Assert.Equal("Post", foreignKey.PrincipalToDependent.Name); + Assert.Equal("Post", foreignKey.PrincipalToDependent!.Name); Assert.Equal("AuthorId", Assert.Single(foreignKey.Properties).Name); - Assert.Equal("Author", foreignKey.DependentToPrincipal.Name); + Assert.Equal("Author", foreignKey.DependentToPrincipal!.Name); } } else @@ -2323,9 +2323,9 @@ public void UseDatabaseNames_and_NoPluralize_work_together( Assert.Equal("User", user.Name); Assert.Equal("Users", user[ScaffoldingAnnotationNames.DbSetName]); Assert.Equal("Id", id.Name); - Assert.Equal("Posts", foreignKey.PrincipalToDependent.Name); + Assert.Equal("Posts", foreignKey.PrincipalToDependent!.Name); Assert.Equal("AuthorId", Assert.Single(foreignKey.Properties).Name); - Assert.Equal("Author", foreignKey.DependentToPrincipal.Name); + Assert.Equal("Author", foreignKey.DependentToPrincipal!.Name); } } @@ -2418,7 +2418,7 @@ public void Scaffold_skip_navigation_for_many_to_many_join_table_ef6() Assert.Equal("Post_Blogs_Source", fk1.GetConstraintName()); var property = Assert.Single(fk1.Properties); Assert.Equal("PostId", property.Name); - Assert.Equal("Post_Id", property.GetColumnName(StoreObjectIdentifier.Table(t3.GetTableName()))); + Assert.Equal("Post_Id", property.GetColumnName(StoreObjectIdentifier.Table(t3.GetTableName()!))); Assert.Equal("Post", fk1.PrincipalEntityType.Name); Assert.Equal(DeleteBehavior.Cascade, fk1.DeleteBehavior); }, @@ -2427,7 +2427,7 @@ public void Scaffold_skip_navigation_for_many_to_many_join_table_ef6() Assert.Equal("Post_Blogs_Target", fk2.GetConstraintName()); var property = Assert.Single(fk2.Properties); Assert.Equal("BlogId", property.Name); - Assert.Equal("Blog_Id", property.GetColumnName(StoreObjectIdentifier.Table(t3.GetTableName()))); + Assert.Equal("Blog_Id", property.GetColumnName(StoreObjectIdentifier.Table(t3.GetTableName()!))); Assert.Equal("Blog", fk2.PrincipalEntityType.Name); Assert.Equal(DeleteBehavior.Cascade, fk2.DeleteBehavior); }); @@ -3403,7 +3403,7 @@ public void Computed_column_when_sql_unknown() var model = _factory.Create(database, new ModelReverseEngineerOptions()); - var column = model.FindEntityType("Table").GetProperty("Column"); - Assert.Empty(column.GetComputedColumnSql()); + var column = model.FindEntityType("Table")!.GetProperty("Column"); + Assert.Empty(column.GetComputedColumnSql()!); } } diff --git a/test/EFCore.Design.Tests/Scaffolding/Internal/ReverseEngineerScaffolderTest.cs b/test/EFCore.Design.Tests/Scaffolding/Internal/ReverseEngineerScaffolderTest.cs index 30abe3f57cd..e9cc4b09fa2 100644 --- a/test/EFCore.Design.Tests/Scaffolding/Internal/ReverseEngineerScaffolderTest.cs +++ b/test/EFCore.Design.Tests/Scaffolding/Internal/ReverseEngineerScaffolderTest.cs @@ -197,8 +197,8 @@ public string ResolveConnectionString(string connectionString) private class TestDatabaseModelFactory : IDatabaseModelFactory { - public string ConnectionString { get; set; } - public string ScaffoldedConnectionString { get; set; } + public string ConnectionString { get; set; } = null!; + public string? ScaffoldedConnectionString { get; set; } public DatabaseModel Create(string connectionString, DatabaseModelFactoryOptions options) { diff --git a/test/EFCore.Design.Tests/Scaffolding/Internal/ScaffoldingTypeMapperSqlServerTest.cs b/test/EFCore.Design.Tests/Scaffolding/Internal/ScaffoldingTypeMapperSqlServerTest.cs index cc5f5dd1267..52296fd30f6 100644 --- a/test/EFCore.Design.Tests/Scaffolding/Internal/ScaffoldingTypeMapperSqlServerTest.cs +++ b/test/EFCore.Design.Tests/Scaffolding/Internal/ScaffoldingTypeMapperSqlServerTest.cs @@ -385,7 +385,7 @@ public void Maps_text_column() } private static void AssertMapping( - TypeScaffoldingInfo mapping, + TypeScaffoldingInfo? mapping, bool inferred, int? maxLength, bool? unicode, @@ -393,6 +393,7 @@ private static void AssertMapping( int? precision, int? scale) { + Assert.NotNull(mapping); Assert.Same(typeof(T), mapping.ClrType); Assert.Equal(inferred, mapping.IsInferred); Assert.Equal(maxLength, mapping.ScaffoldMaxLength); diff --git a/test/EFCore.Design.Tests/Scaffolding/Internal/ScaffoldingTypeMapperSqliteTest.cs b/test/EFCore.Design.Tests/Scaffolding/Internal/ScaffoldingTypeMapperSqliteTest.cs index ec2805364e8..4356afc6505 100644 --- a/test/EFCore.Design.Tests/Scaffolding/Internal/ScaffoldingTypeMapperSqliteTest.cs +++ b/test/EFCore.Design.Tests/Scaffolding/Internal/ScaffoldingTypeMapperSqliteTest.cs @@ -397,8 +397,9 @@ public void Maps_datetime2_column(bool isKeyOrIndex) AssertMapping(mapping, inferred: false, maxLength: null, unicode: null, fixedLength: null); } - private static void AssertMapping(TypeScaffoldingInfo mapping, bool inferred, int? maxLength, bool? unicode, bool? fixedLength) + private static void AssertMapping(TypeScaffoldingInfo? mapping, bool inferred, int? maxLength, bool? unicode, bool? fixedLength) { + Assert.NotNull(mapping); Assert.Same(typeof(T), mapping.ClrType); Assert.Equal(inferred, mapping.IsInferred); Assert.Equal(maxLength, mapping.ScaffoldMaxLength); diff --git a/test/EFCore.Design.Tests/Scaffolding/Internal/TextTemplatingModelGeneratorTest.cs b/test/EFCore.Design.Tests/Scaffolding/Internal/TextTemplatingModelGeneratorTest.cs index ebd39f9a83f..15e6c024556 100644 --- a/test/EFCore.Design.Tests/Scaffolding/Internal/TextTemplatingModelGeneratorTest.cs +++ b/test/EFCore.Design.Tests/Scaffolding/Internal/TextTemplatingModelGeneratorTest.cs @@ -15,7 +15,7 @@ public void HasTemplates_works_when_templates() using var projectDir = new TempDirectory(); var template = Path.Combine(projectDir, "CodeTemplates", "EFCore", "DbContext.t4"); - Directory.CreateDirectory(Path.GetDirectoryName(template)); + Directory.CreateDirectory(Path.GetDirectoryName(template)!); File.Create(template).Close(); var generator = CreateGenerator(); @@ -31,7 +31,7 @@ public void HasTemplates_throws_when_configuration_but_no_context() using var projectDir = new TempDirectory(); var template = Path.Combine(projectDir, "CodeTemplates", "EFCore", "EntityTypeConfiguration.t4"); - Directory.CreateDirectory(Path.GetDirectoryName(template)); + Directory.CreateDirectory(Path.GetDirectoryName(template)!); File.Create(template).Close(); var generator = CreateGenerator(); @@ -59,7 +59,7 @@ public void GenerateModel_uses_templates() using var projectDir = new TempDirectory(); var contextTemplate = Path.Combine(projectDir, "CodeTemplates", "EFCore", "DbContext.t4"); - Directory.CreateDirectory(Path.GetDirectoryName(contextTemplate)); + Directory.CreateDirectory(Path.GetDirectoryName(contextTemplate)!); File.WriteAllText( contextTemplate, "My DbContext template"); @@ -104,7 +104,7 @@ public void GenerateModel_works_when_no_entity_type_template() using var projectDir = new TempDirectory(); var contextTemplate = Path.Combine(projectDir, "CodeTemplates", "EFCore", "DbContext.t4"); - Directory.CreateDirectory(Path.GetDirectoryName(contextTemplate)); + Directory.CreateDirectory(Path.GetDirectoryName(contextTemplate)!); File.WriteAllText( contextTemplate, "My DbContext template"); @@ -135,7 +135,7 @@ public void GenerateModel_works_when_no_context_template_and_csharp() using var projectDir = new TempDirectory(); var template = Path.Combine(projectDir, "CodeTemplates", "EFCore", "EntityType.t4"); - Directory.CreateDirectory(Path.GetDirectoryName(template)); + Directory.CreateDirectory(Path.GetDirectoryName(template)!); File.WriteAllText( template, "My entity type template"); @@ -167,7 +167,7 @@ public void GenerateModel_throws_when_no_context_template_and_not_csharp() using var projectDir = new TempDirectory(); var template = Path.Combine(projectDir, "CodeTemplates", "EFCore", "EntityType.t4"); - Directory.CreateDirectory(Path.GetDirectoryName(template)); + Directory.CreateDirectory(Path.GetDirectoryName(template)!); File.Create(template).Close(); var generator = CreateGenerator(); @@ -194,7 +194,7 @@ public void GenerateModel_sets_session_variables() using var projectDir = new TempDirectory(); var contextTemplate = Path.Combine(projectDir, "CodeTemplates", "EFCore", "DbContext.t4"); - Directory.CreateDirectory(Path.GetDirectoryName(contextTemplate)); + Directory.CreateDirectory(Path.GetDirectoryName(contextTemplate)!); File.WriteAllText( contextTemplate, """ @@ -277,7 +277,7 @@ public void GenerateModel_defaults_to_model_namespace_when_no_context_namespace( using var projectDir = new TempDirectory(); var contextTemplate = Path.Combine(projectDir, "CodeTemplates", "EFCore", "DbContext.t4"); - Directory.CreateDirectory(Path.GetDirectoryName(contextTemplate)); + Directory.CreateDirectory(Path.GetDirectoryName(contextTemplate)!); File.WriteAllText( contextTemplate, @"<#= Session[""NamespaceHint""] #>"); @@ -317,7 +317,7 @@ public void GenerateModel_uses_output_extension() using var projectDir = new TempDirectory(); var contextTemplate = Path.Combine(projectDir, "CodeTemplates", "EFCore", "DbContext.t4"); - Directory.CreateDirectory(Path.GetDirectoryName(contextTemplate)); + Directory.CreateDirectory(Path.GetDirectoryName(contextTemplate)!); File.WriteAllText( contextTemplate, @"<#@ output extension="".vb"" #>"); @@ -366,7 +366,7 @@ public void GenerateModel_warns_when_output_encoding() using var projectDir = new TempDirectory(); var contextTemplate = Path.Combine(projectDir, "CodeTemplates", "EFCore", "DbContext.t4"); - Directory.CreateDirectory(Path.GetDirectoryName(contextTemplate)); + Directory.CreateDirectory(Path.GetDirectoryName(contextTemplate)!); File.WriteAllText( contextTemplate, @"<#@ output encoding=""us-ascii"" #>"); @@ -400,7 +400,7 @@ public void GenerateModel_reports_errors() using var projectDir = new TempDirectory(); var contextTemplate = Path.Combine(projectDir, "CodeTemplates", "EFCore", "DbContext.t4"); - Directory.CreateDirectory(Path.GetDirectoryName(contextTemplate)); + Directory.CreateDirectory(Path.GetDirectoryName(contextTemplate)!); File.WriteAllText( contextTemplate, @"<# Error(""This is an error""); #>"); @@ -436,7 +436,7 @@ public void GenerateModel_reports_warnings() using var projectDir = new TempDirectory(); var contextTemplate = Path.Combine(projectDir, "CodeTemplates", "EFCore", "DbContext.t4"); - Directory.CreateDirectory(Path.GetDirectoryName(contextTemplate)); + Directory.CreateDirectory(Path.GetDirectoryName(contextTemplate)!); File.WriteAllText( contextTemplate, @"<# Warning(""Warning about DbContext""); #>"); @@ -490,7 +490,7 @@ public void GenerateModel_reports_compiler_errors() using var projectDir = new TempDirectory(); var contextTemplate = Path.Combine(projectDir, "CodeTemplates", "EFCore", "DbContext.t4"); - Directory.CreateDirectory(Path.GetDirectoryName(contextTemplate)); + Directory.CreateDirectory(Path.GetDirectoryName(contextTemplate)!); File.WriteAllText( contextTemplate, "<# #error This is a compiler error #>"); @@ -520,7 +520,7 @@ public void GenerateModel_reports_compiler_errors() }); } - private static TemplatedModelGenerator CreateGenerator(IOperationReporter reporter = null) + private static TemplatedModelGenerator CreateGenerator(IOperationReporter? reporter = null) { var serviceCollection = new ServiceCollection() .AddEntityFrameworkDesignTimeServices(reporter); diff --git a/test/EFCore.Design.Tests/TestUtilities/DatabaseColumnRef.cs b/test/EFCore.Design.Tests/TestUtilities/DatabaseColumnRef.cs index a04c85a1d67..eaeb7c02bad 100644 --- a/test/EFCore.Design.Tests/TestUtilities/DatabaseColumnRef.cs +++ b/test/EFCore.Design.Tests/TestUtilities/DatabaseColumnRef.cs @@ -22,25 +22,25 @@ public override bool IsNullable set => throw new NotImplementedException(); } - public override string StoreType + public override string? StoreType { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } - public override string DefaultValueSql + public override string? DefaultValueSql { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } - public override string ComputedColumnSql + public override string? ComputedColumnSql { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } - public override string Comment + public override string? Comment { get => throw new NotImplementedException(); set => throw new NotImplementedException(); diff --git a/test/EFCore.Design.Tests/TestUtilities/DatabaseTableRef.cs b/test/EFCore.Design.Tests/TestUtilities/DatabaseTableRef.cs index e2cffc31958..bef7ac1e066 100644 --- a/test/EFCore.Design.Tests/TestUtilities/DatabaseTableRef.cs +++ b/test/EFCore.Design.Tests/TestUtilities/DatabaseTableRef.cs @@ -7,25 +7,25 @@ namespace Microsoft.EntityFrameworkCore.TestUtilities; internal class DatabaseTableRef : DatabaseTable { - public DatabaseTableRef(string name, string schema = null) + public DatabaseTableRef(string name, string? schema = null) { Name = name; Schema = schema; } - public override DatabaseModel Database + public override DatabaseModel? Database { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } - public override string Comment + public override string? Comment { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } - public override DatabasePrimaryKey PrimaryKey + public override DatabasePrimaryKey? PrimaryKey { get => throw new NotImplementedException(); set => throw new NotImplementedException(); diff --git a/test/EFCore.Design.Tests/TestUtilities/TestDbContextOperations.cs b/test/EFCore.Design.Tests/TestUtilities/TestDbContextOperations.cs index ac5ef9c2971..c078c98ad98 100644 --- a/test/EFCore.Design.Tests/TestUtilities/TestDbContextOperations.cs +++ b/test/EFCore.Design.Tests/TestUtilities/TestDbContextOperations.cs @@ -11,9 +11,9 @@ public class TestDbContextOperations( Assembly startupAssembly, string project, string projectDir, - string rootNamespace, - string language, + string? rootNamespace, + string? language, bool nullable, - string[] args, + string[]? args, AppServiceProviderFactory appServicesFactory) : DbContextOperations( reporter, assembly, startupAssembly, project, projectDir, rootNamespace, language, nullable, args, appServicesFactory); diff --git a/test/EFCore.Design.Tests/TestUtilities/TestMigrationsOperations.cs b/test/EFCore.Design.Tests/TestUtilities/TestMigrationsOperations.cs index 615193b0972..aaea763d56c 100644 --- a/test/EFCore.Design.Tests/TestUtilities/TestMigrationsOperations.cs +++ b/test/EFCore.Design.Tests/TestUtilities/TestMigrationsOperations.cs @@ -10,7 +10,7 @@ public class TestMigrationsOperations( Assembly assembly, Assembly startupAssembly, string projectDir, - string rootNamespace, - string language, + string? rootNamespace, + string? language, bool nullable, - string[] args) : MigrationsOperations(reporter, assembly, startupAssembly, projectDir, rootNamespace, language, nullable, args); + string[]? args) : MigrationsOperations(reporter, assembly, startupAssembly, projectDir, rootNamespace, language, nullable, args); diff --git a/test/EFCore.Relational.Specification.Tests/BulkUpdates/Inheritance/FiltersInheritanceBulkUpdatesRelationalTestBase.cs b/test/EFCore.Relational.Specification.Tests/BulkUpdates/Inheritance/FiltersInheritanceBulkUpdatesRelationalTestBase.cs index 24bf1c5b4a1..6db759a57c6 100644 --- a/test/EFCore.Relational.Specification.Tests/BulkUpdates/Inheritance/FiltersInheritanceBulkUpdatesRelationalTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/BulkUpdates/Inheritance/FiltersInheritanceBulkUpdatesRelationalTestBase.cs @@ -5,8 +5,6 @@ namespace Microsoft.EntityFrameworkCore.BulkUpdates.Inheritance; -#nullable disable - public abstract class FiltersInheritanceBulkUpdatesRelationalTestBase : FiltersInheritanceBulkUpdatesTestBase where TFixture : InheritanceBulkUpdatesRelationalFixtureBase, new() { diff --git a/test/EFCore.Relational.Specification.Tests/BulkUpdates/Inheritance/InheritanceBulkUpdatesRelationalFixtureBase.cs b/test/EFCore.Relational.Specification.Tests/BulkUpdates/Inheritance/InheritanceBulkUpdatesRelationalFixtureBase.cs index de2d69bd51f..921bea13ecb 100644 --- a/test/EFCore.Relational.Specification.Tests/BulkUpdates/Inheritance/InheritanceBulkUpdatesRelationalFixtureBase.cs +++ b/test/EFCore.Relational.Specification.Tests/BulkUpdates/Inheritance/InheritanceBulkUpdatesRelationalFixtureBase.cs @@ -5,8 +5,6 @@ namespace Microsoft.EntityFrameworkCore.BulkUpdates.Inheritance; -#nullable disable - public abstract class InheritanceBulkUpdatesRelationalFixtureBase : InheritanceBulkUpdatesFixtureBase, ITestSqlLoggerFactory { protected override void OnModelCreating(ModelBuilder modelBuilder, DbContext context) diff --git a/test/EFCore.Relational.Specification.Tests/BulkUpdates/Inheritance/InheritanceBulkUpdatesRelationalTestBase.cs b/test/EFCore.Relational.Specification.Tests/BulkUpdates/Inheritance/InheritanceBulkUpdatesRelationalTestBase.cs index 333780f3cba..f152fb78c87 100644 --- a/test/EFCore.Relational.Specification.Tests/BulkUpdates/Inheritance/InheritanceBulkUpdatesRelationalTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/BulkUpdates/Inheritance/InheritanceBulkUpdatesRelationalTestBase.cs @@ -5,8 +5,6 @@ namespace Microsoft.EntityFrameworkCore.BulkUpdates.Inheritance; -#nullable disable - public abstract class InheritanceBulkUpdatesRelationalTestBase : InheritanceBulkUpdatesTestBase where TFixture : InheritanceBulkUpdatesRelationalFixtureBase, new() { diff --git a/test/EFCore.Relational.Specification.Tests/BulkUpdates/Inheritance/TPCFiltersInheritanceBulkUpdatesTestBase.cs b/test/EFCore.Relational.Specification.Tests/BulkUpdates/Inheritance/TPCFiltersInheritanceBulkUpdatesTestBase.cs index cc0f633bd74..e4d2d70df43 100644 --- a/test/EFCore.Relational.Specification.Tests/BulkUpdates/Inheritance/TPCFiltersInheritanceBulkUpdatesTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/BulkUpdates/Inheritance/TPCFiltersInheritanceBulkUpdatesTestBase.cs @@ -3,8 +3,6 @@ namespace Microsoft.EntityFrameworkCore.BulkUpdates.Inheritance; -#nullable disable - public abstract class TPCFiltersInheritanceBulkUpdatesTestBase(TFixture fixture, ITestOutputHelper testOutputHelper) : FiltersInheritanceBulkUpdatesRelationalTestBase(fixture, testOutputHelper) where TFixture : TPCInheritanceBulkUpdatesFixture, new() diff --git a/test/EFCore.Relational.Specification.Tests/BulkUpdates/Inheritance/TPCInheritanceBulkUpdatesFixture.cs b/test/EFCore.Relational.Specification.Tests/BulkUpdates/Inheritance/TPCInheritanceBulkUpdatesFixture.cs index c32dd53fdae..2c24572c7e4 100644 --- a/test/EFCore.Relational.Specification.Tests/BulkUpdates/Inheritance/TPCInheritanceBulkUpdatesFixture.cs +++ b/test/EFCore.Relational.Specification.Tests/BulkUpdates/Inheritance/TPCInheritanceBulkUpdatesFixture.cs @@ -5,8 +5,6 @@ namespace Microsoft.EntityFrameworkCore.BulkUpdates.Inheritance; -#nullable disable - public abstract class TPCInheritanceBulkUpdatesFixture : InheritanceBulkUpdatesRelationalFixtureBase { protected override string StoreName diff --git a/test/EFCore.Relational.Specification.Tests/BulkUpdates/Inheritance/TPCInheritanceBulkUpdatesTestBase.cs b/test/EFCore.Relational.Specification.Tests/BulkUpdates/Inheritance/TPCInheritanceBulkUpdatesTestBase.cs index 7baf58db4ff..5d014aed2b8 100644 --- a/test/EFCore.Relational.Specification.Tests/BulkUpdates/Inheritance/TPCInheritanceBulkUpdatesTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/BulkUpdates/Inheritance/TPCInheritanceBulkUpdatesTestBase.cs @@ -3,8 +3,6 @@ namespace Microsoft.EntityFrameworkCore.BulkUpdates.Inheritance; -#nullable disable - public abstract class TPCInheritanceBulkUpdatesTestBase : InheritanceBulkUpdatesRelationalTestBase where TFixture : TPCInheritanceBulkUpdatesFixture, new() { diff --git a/test/EFCore.Relational.Specification.Tests/BulkUpdates/Inheritance/TPHInheritanceBulkUpdatesFixture.cs b/test/EFCore.Relational.Specification.Tests/BulkUpdates/Inheritance/TPHInheritanceBulkUpdatesFixture.cs index a4353130ee7..b91affeab07 100644 --- a/test/EFCore.Relational.Specification.Tests/BulkUpdates/Inheritance/TPHInheritanceBulkUpdatesFixture.cs +++ b/test/EFCore.Relational.Specification.Tests/BulkUpdates/Inheritance/TPHInheritanceBulkUpdatesFixture.cs @@ -5,8 +5,6 @@ namespace Microsoft.EntityFrameworkCore.BulkUpdates.Inheritance; -#nullable disable - public abstract class TPHInheritanceBulkUpdatesFixture : InheritanceBulkUpdatesRelationalFixtureBase { protected override string StoreName diff --git a/test/EFCore.Relational.Specification.Tests/BulkUpdates/Inheritance/TPHInheritanceBulkUpdatesTestBase.cs b/test/EFCore.Relational.Specification.Tests/BulkUpdates/Inheritance/TPHInheritanceBulkUpdatesTestBase.cs index b96d3133c17..bbb2dff0197 100644 --- a/test/EFCore.Relational.Specification.Tests/BulkUpdates/Inheritance/TPHInheritanceBulkUpdatesTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/BulkUpdates/Inheritance/TPHInheritanceBulkUpdatesTestBase.cs @@ -3,8 +3,6 @@ namespace Microsoft.EntityFrameworkCore.BulkUpdates.Inheritance; -#nullable disable - public abstract class TPHInheritanceBulkUpdatesTestBase(TFixture fixture, ITestOutputHelper testOutputHelper) : InheritanceBulkUpdatesRelationalTestBase(fixture, testOutputHelper) where TFixture : InheritanceBulkUpdatesRelationalFixtureBase, new(); diff --git a/test/EFCore.Relational.Specification.Tests/BulkUpdates/Inheritance/TPTFiltersInheritanceBulkUpdatesTestBase.cs b/test/EFCore.Relational.Specification.Tests/BulkUpdates/Inheritance/TPTFiltersInheritanceBulkUpdatesTestBase.cs index 304ec648526..b4ecd7488ff 100644 --- a/test/EFCore.Relational.Specification.Tests/BulkUpdates/Inheritance/TPTFiltersInheritanceBulkUpdatesTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/BulkUpdates/Inheritance/TPTFiltersInheritanceBulkUpdatesTestBase.cs @@ -3,8 +3,6 @@ namespace Microsoft.EntityFrameworkCore.BulkUpdates.Inheritance; -#nullable disable - public abstract class TPTFiltersInheritanceBulkUpdatesTestBase(TFixture fixture, ITestOutputHelper testOutputHelper) : FiltersInheritanceBulkUpdatesRelationalTestBase(fixture, testOutputHelper) where TFixture : TPTInheritanceBulkUpdatesFixture, new() diff --git a/test/EFCore.Relational.Specification.Tests/BulkUpdates/Inheritance/TPTInheritanceBulkUpdatesFixture.cs b/test/EFCore.Relational.Specification.Tests/BulkUpdates/Inheritance/TPTInheritanceBulkUpdatesFixture.cs index 039e59da731..5dd885e4af2 100644 --- a/test/EFCore.Relational.Specification.Tests/BulkUpdates/Inheritance/TPTInheritanceBulkUpdatesFixture.cs +++ b/test/EFCore.Relational.Specification.Tests/BulkUpdates/Inheritance/TPTInheritanceBulkUpdatesFixture.cs @@ -5,8 +5,6 @@ namespace Microsoft.EntityFrameworkCore.BulkUpdates.Inheritance; -#nullable disable - public abstract class TPTInheritanceBulkUpdatesFixture : InheritanceBulkUpdatesRelationalFixtureBase { protected override string StoreName diff --git a/test/EFCore.Relational.Specification.Tests/BulkUpdates/Inheritance/TPTInheritanceBulkUpdatesTestBase.cs b/test/EFCore.Relational.Specification.Tests/BulkUpdates/Inheritance/TPTInheritanceBulkUpdatesTestBase.cs index 6a323b1abad..d942f081048 100644 --- a/test/EFCore.Relational.Specification.Tests/BulkUpdates/Inheritance/TPTInheritanceBulkUpdatesTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/BulkUpdates/Inheritance/TPTInheritanceBulkUpdatesTestBase.cs @@ -3,8 +3,6 @@ namespace Microsoft.EntityFrameworkCore.BulkUpdates.Inheritance; -#nullable disable - public abstract class TPTInheritanceBulkUpdatesTestBase : InheritanceBulkUpdatesRelationalTestBase where TFixture : TPTInheritanceBulkUpdatesFixture, new() { diff --git a/test/EFCore.Relational.Specification.Tests/BulkUpdates/NonSharedModelBulkUpdatesRelationalTestBase.cs b/test/EFCore.Relational.Specification.Tests/BulkUpdates/NonSharedModelBulkUpdatesRelationalTestBase.cs index 13b0eafc9c7..2fd97dd0374 100644 --- a/test/EFCore.Relational.Specification.Tests/BulkUpdates/NonSharedModelBulkUpdatesRelationalTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/BulkUpdates/NonSharedModelBulkUpdatesRelationalTestBase.cs @@ -5,8 +5,6 @@ namespace Microsoft.EntityFrameworkCore.BulkUpdates; -#nullable disable - public abstract class NonSharedModelBulkUpdatesRelationalTestBase(NonSharedFixture fixture) : NonSharedModelBulkUpdatesTestBase(fixture) { protected override string NonSharedStoreName @@ -162,8 +160,8 @@ public class Foo [DatabaseGenerated(DatabaseGeneratedOption.None)] public int Id { get; set; } - public string Data { get; set; } - public ComplexThing ComplexThing { get; set; } + public string? Data { get; set; } + public ComplexThing ComplexThing { get; set; } = null!; } public class ComplexThing diff --git a/test/EFCore.Relational.Specification.Tests/BulkUpdates/NorthwindBulkUpdatesRelationalFixture.cs b/test/EFCore.Relational.Specification.Tests/BulkUpdates/NorthwindBulkUpdatesRelationalFixture.cs index 35d9d92d5ac..e4ea8e89ea7 100644 --- a/test/EFCore.Relational.Specification.Tests/BulkUpdates/NorthwindBulkUpdatesRelationalFixture.cs +++ b/test/EFCore.Relational.Specification.Tests/BulkUpdates/NorthwindBulkUpdatesRelationalFixture.cs @@ -3,8 +3,6 @@ namespace Microsoft.EntityFrameworkCore.BulkUpdates; -#nullable disable - public abstract class NorthwindBulkUpdatesRelationalFixture : NorthwindBulkUpdatesFixture, ITestSqlLoggerFactory where TModelCustomizer : ITestModelCustomizer, new() diff --git a/test/EFCore.Relational.Specification.Tests/BulkUpdates/NorthwindBulkUpdatesRelationalTestBase.cs b/test/EFCore.Relational.Specification.Tests/BulkUpdates/NorthwindBulkUpdatesRelationalTestBase.cs index 204aa05aec7..4e60895f5d8 100644 --- a/test/EFCore.Relational.Specification.Tests/BulkUpdates/NorthwindBulkUpdatesRelationalTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/BulkUpdates/NorthwindBulkUpdatesRelationalTestBase.cs @@ -5,8 +5,6 @@ namespace Microsoft.EntityFrameworkCore.BulkUpdates; -#nullable disable - public abstract class NorthwindBulkUpdatesRelationalTestBase : NorthwindBulkUpdatesTestBase where TFixture : NorthwindBulkUpdatesRelationalFixture, new() { diff --git a/test/EFCore.Relational.Specification.Tests/CommandInterceptionTestBase.cs b/test/EFCore.Relational.Specification.Tests/CommandInterceptionTestBase.cs index ceed6a31cfe..645e1337676 100644 --- a/test/EFCore.Relational.Specification.Tests/CommandInterceptionTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/CommandInterceptionTestBase.cs @@ -3,12 +3,11 @@ using System.Collections; using System.Data; +using System.Diagnostics.CodeAnalysis; // ReSharper disable InconsistentNaming namespace Microsoft.EntityFrameworkCore; -#nullable disable - public abstract class CommandInterceptionTestBase(InterceptionTestBase.InterceptionFixtureBase fixture) : InterceptionTestBase(fixture) { [Theory, InlineData(false, false), InlineData(true, false), InlineData(false, true), InlineData(true, true)] @@ -472,7 +471,7 @@ public override DbCommand CommandInitialized(CommandEndEventData eventData, DbCo public virtual async Task Intercept_non_query_to_mutate_command(bool async, bool inject) { var interceptor = new MutatingNonQueryCommandInterceptor(this); - var context = inject ? await CreateContextAsync(null, interceptor) : await CreateContextAsync(interceptor); + var context = inject ? await CreateContextAsync(null!, interceptor) : await CreateContextAsync(interceptor); using (context) { using (context.Database.BeginTransaction()) @@ -580,7 +579,7 @@ public override async ValueTask> ReaderExecutin private static DbCommand CreateNewCommand(DbCommand command) { - var newCommand = command.Connection.CreateCommand(); + var newCommand = command.Connection!.CreateCommand(); newCommand.CommandText = command.CommandText.Replace("Singularity", "Brane"); return newCommand; @@ -626,7 +625,7 @@ public override InterceptionResult ScalarExecuting( base.ScalarExecuting(command, eventData, result); // Note: this DbCommand will not get disposed...can be problematic on some providers - return InterceptionResult.SuppressWithResult(CreateNewCommand(command).ExecuteScalar()); + return InterceptionResult.SuppressWithResult(CreateNewCommand(command).ExecuteScalar()!); } public override async ValueTask> ScalarExecutingAsync( @@ -638,12 +637,12 @@ public override async ValueTask> ScalarExecutingAsync await base.ScalarExecutingAsync(command, eventData, result, cancellationToken); // Note: this DbCommand will not get disposed...can be problematic on some providers - return InterceptionResult.SuppressWithResult(await CreateNewCommand(command).ExecuteScalarAsync(cancellationToken)); + return InterceptionResult.SuppressWithResult((await CreateNewCommand(command).ExecuteScalarAsync(cancellationToken))!); } private static DbCommand CreateNewCommand(DbCommand command) { - var newCommand = command.Connection.CreateCommand(); + var newCommand = command.Connection!.CreateCommand(); newCommand.CommandText = "SELECT 2"; return newCommand; @@ -654,7 +653,7 @@ private static DbCommand CreateNewCommand(DbCommand command) public virtual async Task Intercept_non_query_to_replace_execution(bool async, bool inject) { var interceptor = new QueryReplacingNonQueryCommandInterceptor(this); - var context = inject ? await CreateContextAsync(null, interceptor) : await CreateContextAsync(interceptor); + var context = inject ? await CreateContextAsync(null!, interceptor) : await CreateContextAsync(interceptor); using (context) { using (context.Database.BeginTransaction()) @@ -708,7 +707,7 @@ public override async ValueTask> NonQueryExecutingAsync( private DbCommand CreateNewCommand(DbCommand command) { - var newCommand = command.Connection.CreateCommand(); + var newCommand = command.Connection!.CreateCommand(); newCommand.Transaction = command.Transaction; newCommand.CommandText = commandText; @@ -884,20 +883,20 @@ protected class ResultReplacingScalarCommandInterceptor() : CommandInterceptorBa { public const string InterceptedResult = "Bet you weren't expecting a string!"; - public override object ScalarExecuted( + public override object? ScalarExecuted( DbCommand command, CommandExecutedEventData eventData, - object result) + object? result) { base.ScalarExecuted(command, eventData, result); return InterceptedResult; } - public override async ValueTask ScalarExecutedAsync( + public override async ValueTask ScalarExecutedAsync( DbCommand command, CommandExecutedEventData eventData, - object result, + object? result, CancellationToken cancellationToken = default) { await base.ScalarExecutedAsync(command, eventData, result, cancellationToken); @@ -1217,7 +1216,7 @@ public virtual async Task Intercept_query_with_two_injected_interceptors(bool as var injectedInterceptor1 = new MutatingReaderCommandInterceptor(); var injectedInterceptor2 = new ResultReplacingReaderCommandInterceptor(); - using var context = await CreateContextAsync(null, injectedInterceptor1, injectedInterceptor2); + using var context = await CreateContextAsync(null!, injectedInterceptor1, injectedInterceptor2); await TestCompoisteQueryInterceptors(context, injectedInterceptor2, injectedInterceptor1, async); } @@ -1225,7 +1224,7 @@ public virtual async Task Intercept_query_with_two_injected_interceptors(bool as public virtual async Task Intercept_scalar_with_two_injected_interceptors(bool async) { using var context = await CreateContextAsync( - null, + null!, new MutatingScalarCommandInterceptor(), new ResultReplacingScalarCommandInterceptor()); await TestCompositeScalarInterceptors(context, async); } @@ -1234,7 +1233,7 @@ public virtual async Task Intercept_scalar_with_two_injected_interceptors(bool a public virtual async Task Intercept_non_query_with_two_injected_interceptors(bool async) { using var context = await CreateContextAsync( - null, + null!, new MutatingNonQueryCommandInterceptor(this), new ResultReplacingNonQueryCommandInterceptor()); await TestCompositeNonQueryInterceptors(context, async); } @@ -1392,12 +1391,13 @@ public override void Cancel() public override int ExecuteNonQuery() => _command.ExecuteNonQuery(); - public override object ExecuteScalar() + public override object? ExecuteScalar() => _command.ExecuteScalar(); public override void Prepare() => _command.Prepare(); + [AllowNull] public override string CommandText { get => _command.CommandText; @@ -1422,7 +1422,7 @@ public override UpdateRowSource UpdatedRowSource set => _command.UpdatedRowSource = value; } - protected override DbConnection DbConnection + protected override DbConnection? DbConnection { get => _command.Connection; set => _command.Connection = value; @@ -1431,7 +1431,7 @@ protected override DbConnection DbConnection protected override DbParameterCollection DbParameterCollection => _command.Parameters; - protected override DbTransaction DbTransaction + protected override DbTransaction? DbTransaction { get => _command.Transaction; set => _command.Transaction = value; @@ -1481,13 +1481,13 @@ public override bool GetBoolean(int ordinal) public override byte GetByte(int ordinal) => throw new NotImplementedException(); - public override long GetBytes(int ordinal, long dataOffset, byte[] buffer, int bufferOffset, int length) + public override long GetBytes(int ordinal, long dataOffset, byte[]? buffer, int bufferOffset, int length) => throw new NotImplementedException(); public override char GetChar(int ordinal) => throw new NotImplementedException(); - public override long GetChars(int ordinal, long dataOffset, char[] buffer, int bufferOffset, int length) + public override long GetChars(int ordinal, long dataOffset, char[]? buffer, int bufferOffset, int length) => throw new NotImplementedException(); public override string GetDataTypeName(int ordinal) @@ -1574,8 +1574,8 @@ protected static void AssertErrorOutcome(DbContext context, CommandInterceptorBa protected static void AssertExecutedEvents(ITestDiagnosticListener listener) => listener.AssertEventsInOrder( - RelationalEventId.CommandExecuting.Name, - RelationalEventId.CommandExecuted.Name); + RelationalEventId.CommandExecuting.Name!, + RelationalEventId.CommandExecuted.Name!); protected static void AssertSql(string expected, string actual) => Assert.Equal( @@ -1584,9 +1584,9 @@ protected static void AssertSql(string expected, string actual) protected abstract class CommandInterceptorBase(DbCommandMethod commandMethod) : IDbCommandInterceptor { - public DbContext Context { get; set; } - public Exception Exception { get; set; } - public string CommandText { get; set; } + public DbContext Context { get; set; } = null!; + public Exception Exception { get; set; } = null!; + public string CommandText { get; set; } = null!; public Guid CommandId { get; set; } public Guid ConnectionId { get; set; } public CommandSource CommandSource { get; set; } @@ -1716,10 +1716,10 @@ public virtual DbDataReader ReaderExecuted( return result; } - public virtual object ScalarExecuted( + public virtual object? ScalarExecuted( DbCommand command, CommandExecutedEventData eventData, - object result) + object? result) { Assert.False(eventData.IsAsync); SyncCalled = true; @@ -1753,10 +1753,10 @@ public virtual ValueTask ReaderExecutedAsync( return ValueTask.FromResult(result); } - public virtual ValueTask ScalarExecutedAsync( + public virtual ValueTask ScalarExecutedAsync( DbCommand command, CommandExecutedEventData eventData, - object result, + object? result, CancellationToken cancellationToken = default) { Assert.True(eventData.IsAsync); diff --git a/test/EFCore.Relational.Specification.Tests/ConcurrencyDetectorDisabledRelationalTestBase.cs b/test/EFCore.Relational.Specification.Tests/ConcurrencyDetectorDisabledRelationalTestBase.cs index 20b2d14bf47..a79519de18d 100644 --- a/test/EFCore.Relational.Specification.Tests/ConcurrencyDetectorDisabledRelationalTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/ConcurrencyDetectorDisabledRelationalTestBase.cs @@ -5,8 +5,6 @@ namespace Microsoft.EntityFrameworkCore; -#nullable disable - public abstract class ConcurrencyDetectorDisabledRelationalTestBase(TFixture fixture) : ConcurrencyDetectorDisabledTestBase(fixture) where TFixture : ConcurrencyDetectorTestBase.ConcurrencyDetectorFixtureBase, new() diff --git a/test/EFCore.Relational.Specification.Tests/ConcurrencyDetectorEnabledRelationalTestBase.cs b/test/EFCore.Relational.Specification.Tests/ConcurrencyDetectorEnabledRelationalTestBase.cs index 8e1ba908a04..4faf388c00f 100644 --- a/test/EFCore.Relational.Specification.Tests/ConcurrencyDetectorEnabledRelationalTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/ConcurrencyDetectorEnabledRelationalTestBase.cs @@ -5,8 +5,6 @@ namespace Microsoft.EntityFrameworkCore; -#nullable disable - public abstract class ConcurrencyDetectorEnabledRelationalTestBase(TFixture fixture) : ConcurrencyDetectorEnabledTestBase(fixture) where TFixture : ConcurrencyDetectorTestBase.ConcurrencyDetectorFixtureBase, new() diff --git a/test/EFCore.Relational.Specification.Tests/ConnectionInterceptionTestBase.cs b/test/EFCore.Relational.Specification.Tests/ConnectionInterceptionTestBase.cs index a7d10fa6b69..c2a50b2b0e8 100644 --- a/test/EFCore.Relational.Specification.Tests/ConnectionInterceptionTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/ConnectionInterceptionTestBase.cs @@ -871,8 +871,8 @@ private static void AssertErrorOnOpen(DbContext context, ConnectionInterceptor i private static void AsertOpenCloseEvents(ITestDiagnosticListener listener) => listener.AssertEventsInOrder( - RelationalEventId.ConnectionOpening.Name, - RelationalEventId.ConnectionOpened.Name, - RelationalEventId.ConnectionClosing.Name, - RelationalEventId.ConnectionClosed.Name); + RelationalEventId.ConnectionOpening.Name!, + RelationalEventId.ConnectionOpened.Name!, + RelationalEventId.ConnectionClosing.Name!, + RelationalEventId.ConnectionClosed.Name!); } diff --git a/test/EFCore.Relational.Specification.Tests/DataAnnotationRelationalTestBase.cs b/test/EFCore.Relational.Specification.Tests/DataAnnotationRelationalTestBase.cs index 8d69f57f51a..ed10bb55d4c 100644 --- a/test/EFCore.Relational.Specification.Tests/DataAnnotationRelationalTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/DataAnnotationRelationalTestBase.cs @@ -6,8 +6,6 @@ namespace Microsoft.EntityFrameworkCore; -#nullable disable - public abstract class DataAnnotationRelationalTestBase(TFixture fixture) : DataAnnotationTestBase(fixture) where TFixture : DataAnnotationRelationalTestBase.DataAnnotationRelationalFixtureBase, new() { @@ -31,10 +29,10 @@ public virtual void ForeignKey_to_ForeignKey_on_many_to_many() var model = Validate(modelBuilder); - var login = modelBuilder.Model.FindEntityType(typeof(Login16)); - var logins = login.FindSkipNavigation(nameof(Login16.Profile16s)); + var login = modelBuilder.Model.FindEntityType(typeof(Login16))!; + var logins = login.FindSkipNavigation(nameof(Login16.Profile16s))!; var join = logins.JoinEntityType; - Assert.Equal(2, join.GetProperties().Count()); + Assert.Equal(2, join!.GetProperties().Count()); Assert.False(GetProperty(model, "Login16Id").IsForeignKey()); Assert.False(GetProperty(model, "Profile16Id").IsForeignKey()); } @@ -44,7 +42,7 @@ public class Login16 public int Login16Id { get; set; } [ForeignKey("Login16Id")] - public virtual ICollection Profile16s { get; set; } + public virtual ICollection Profile16s { get; set; } = []; } public class Profile16 @@ -52,7 +50,7 @@ public class Profile16 public int Profile16Id { get; set; } [ForeignKey("Profile16Id")] - public virtual ICollection Login16s { get; set; } + public virtual ICollection Login16s { get; set; } = []; } [Fact] @@ -123,33 +121,33 @@ protected class Animal [Key] public int Key { get; set; } - public string Species { get; set; } + public string? Species { get; set; } } [Table("Pets")] protected class Pet : Animal { - public string Name { get; set; } + public string? Name { get; set; } [Column("FavoritePetFood_Id"), ForeignKey(nameof(FavoritePetFood))] public int? FavoritePetFoodId { get; set; } - public PetFood FavoritePetFood { get; set; } + public PetFood? FavoritePetFood { get; set; } [Required] - public PetTag Tag { get; set; } + public PetTag Tag { get; set; } = null!; } [Table("Cats")] protected sealed class Cat : Pet { - public string EducationLevel { get; set; } + public string? EducationLevel { get; set; } } [Table("Dogs")] protected sealed class Dog : Pet { - public string FavoriteToy { get; set; } + public string? FavoriteToy { get; set; } } [Owned] @@ -165,6 +163,6 @@ public sealed class PetFood [DatabaseGenerated(DatabaseGeneratedOption.Identity), Column("PetFoods_Id")] public int PetFoodId { get; set; } - public string FoodName { get; set; } + public string? FoodName { get; set; } } } diff --git a/test/EFCore.Relational.Specification.Tests/DesignTimeTestBase.cs b/test/EFCore.Relational.Specification.Tests/DesignTimeTestBase.cs index 4c540f116a4..598b180620d 100644 --- a/test/EFCore.Relational.Specification.Tests/DesignTimeTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/DesignTimeTestBase.cs @@ -3,8 +3,6 @@ namespace Microsoft.EntityFrameworkCore; -#nullable disable - public abstract class DesignTimeTestBase(TFixture fixture) : IClassFixture where TFixture : DesignTimeTestBase.DesignTimeFixtureBase { @@ -20,8 +18,8 @@ public void Can_get_reverse_engineering_services() .AddEntityFrameworkDesignTimeServices(); ((IDesignTimeServices)Activator.CreateInstance( ProviderAssembly.GetType( - ProviderAssembly.GetCustomAttribute().TypeName, - throwOnError: true))!) + ProviderAssembly.GetCustomAttribute()!.TypeName, + throwOnError: true)!)!) .ConfigureDesignTimeServices(serviceCollection); using var services = serviceCollection.BuildServiceProvider(validateScopes: true); @@ -39,8 +37,8 @@ public void Can_get_migrations_services() .AddDbContextDesignTimeServices(context); ((IDesignTimeServices)Activator.CreateInstance( ProviderAssembly.GetType( - ProviderAssembly.GetCustomAttribute().TypeName, - throwOnError: true))!) + ProviderAssembly.GetCustomAttribute()!.TypeName, + throwOnError: true)!)!) .ConfigureDesignTimeServices(serviceCollection); using var services = serviceCollection.BuildServiceProvider(validateScopes: true); diff --git a/test/EFCore.Relational.Specification.Tests/EntitySplittingTestBase.cs b/test/EFCore.Relational.Specification.Tests/EntitySplittingTestBase.cs index cc54360ebce..2a5570e052c 100644 --- a/test/EFCore.Relational.Specification.Tests/EntitySplittingTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/EntitySplittingTestBase.cs @@ -5,8 +5,6 @@ namespace Microsoft.EntityFrameworkCore; -#nullable disable - public abstract class EntitySplittingTestBase : NonSharedModelTestBase, IClassFixture { protected EntitySplittingTestBase(NonSharedFixture fixture, ITestOutputHelper testOutputHelper) @@ -82,7 +80,7 @@ protected override string NonSharedStoreName protected TestSqlLoggerFactory TestSqlLoggerFactory => (TestSqlLoggerFactory)ListLoggerFactory; - protected ContextFactory ContextFactory { get; private set; } + protected ContextFactory? ContextFactory { get; private set; } protected void AssertSql(params string[] expected) => TestSqlLoggerFactory.AssertBaseline(expected); @@ -101,8 +99,8 @@ protected virtual void OnModelCreating(ModelBuilder modelBuilder) protected async Task InitializeAsync( Action onModelCreating, - Func onConfiguring = null, - Func seed = null, + Func? onConfiguring = null, + Func? seed = null, bool sensitiveLogEnabled = true) => ContextFactory = await InitializeNonSharedTest( onModelCreating, @@ -118,7 +116,7 @@ protected async Task InitializeAsync( ); protected virtual EntitySplittingContext CreateContext() - => ContextFactory.CreateDbContext(); + => ContextFactory!.CreateDbContext(); public override async ValueTask DisposeAsync() { @@ -129,15 +127,15 @@ public override async ValueTask DisposeAsync() protected class EntitySplittingContext(DbContextOptions options) : PoolableDbContext(options) { - public DbSet MeterReadings { get; set; } + public DbSet MeterReadings { get; set; } = null!; } protected class MeterReading { public int Id { get; set; } public MeterReadingStatus? ReadingStatus { get; set; } - public string CurrentRead { get; set; } - public string PreviousRead { get; set; } + public string? CurrentRead { get; set; } + public string? PreviousRead { get; set; } } protected enum MeterReadingStatus diff --git a/test/EFCore.Relational.Specification.Tests/F1RelationalFixture.cs b/test/EFCore.Relational.Specification.Tests/F1RelationalFixture.cs index 6dab7ea72ab..e7e3305b895 100644 --- a/test/EFCore.Relational.Specification.Tests/F1RelationalFixture.cs +++ b/test/EFCore.Relational.Specification.Tests/F1RelationalFixture.cs @@ -5,8 +5,6 @@ namespace Microsoft.EntityFrameworkCore; -#nullable disable - public abstract class F1RelationalFixture : F1FixtureBase { public TestSqlLoggerFactory TestSqlLoggerFactory diff --git a/test/EFCore.Relational.Specification.Tests/LoggingRelationalTestBase.cs b/test/EFCore.Relational.Specification.Tests/LoggingRelationalTestBase.cs index f18f4c74ad3..1e7ff36d217 100644 --- a/test/EFCore.Relational.Specification.Tests/LoggingRelationalTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/LoggingRelationalTestBase.cs @@ -7,8 +7,6 @@ namespace Microsoft.EntityFrameworkCore; -#nullable disable - public abstract class LoggingRelationalTestBase : LoggingTestBase where TBuilder : RelationalDbContextOptionsBuilder where TExtension : RelationalOptionsExtension, new() @@ -69,7 +67,7 @@ protected class IndexPropertiesBothMappedAndNotMappedToTableContext(DbContextOpt protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity(); - modelBuilder.Entity().ToTable((string)null).HasIndex(nameof(Animal.Name), nameof(Cat.Identity)); + modelBuilder.Entity().ToTable((string?)null).HasIndex(nameof(Animal.Name), nameof(Cat.Identity)); } } @@ -135,7 +133,7 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) protected abstract DbContextOptionsBuilder CreateOptionsBuilder( IServiceCollection services, - Action> relationalAction); + Action>? relationalAction); protected override DbContextOptionsBuilder CreateOptionsBuilder(IServiceCollection services) => CreateOptionsBuilder(services, null); diff --git a/test/EFCore.Relational.Specification.Tests/ManyToManyTrackingRelationalTestBase.cs b/test/EFCore.Relational.Specification.Tests/ManyToManyTrackingRelationalTestBase.cs index 4414b008996..4fd29724bae 100644 --- a/test/EFCore.Relational.Specification.Tests/ManyToManyTrackingRelationalTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/ManyToManyTrackingRelationalTestBase.cs @@ -5,8 +5,6 @@ namespace Microsoft.EntityFrameworkCore; -#nullable disable - public abstract class ManyToManyTrackingRelationalTestBase(TFixture fixture) : ManyToManyTrackingTestBase(fixture) where TFixture : ManyToManyTrackingRelationalTestBase.ManyToManyTrackingRelationalFixture { diff --git a/test/EFCore.Relational.Specification.Tests/Migrations/MigrationsInfrastructureTestBase.cs b/test/EFCore.Relational.Specification.Tests/Migrations/MigrationsInfrastructureTestBase.cs index 71bc58f68af..f20444df781 100644 --- a/test/EFCore.Relational.Specification.Tests/Migrations/MigrationsInfrastructureTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/Migrations/MigrationsInfrastructureTestBase.cs @@ -5,8 +5,6 @@ namespace Microsoft.EntityFrameworkCore.Migrations; -#nullable disable - public abstract class MigrationsInfrastructureTestBase : IClassFixture where TFixture : MigrationsInfrastructureFixtureBase, new() { @@ -20,9 +18,9 @@ protected MigrationsInfrastructureTestBase(TFixture fixture) Fixture.ResetCounts(); } - protected string Sql { get; private set; } + protected string Sql { get; private set; } = null!; - protected string ActiveProvider { get; private set; } + protected string? ActiveProvider { get; private set; } public static readonly IEnumerable IsAsyncData = [[false], [true]]; @@ -561,7 +559,7 @@ private Task SetAndExecuteSqlAsync(string value, bool append = false) public abstract class MigrationsInfrastructureFixtureBase : SharedStoreFixtureBase { - public static string ActiveProvider { get; set; } + public static string? ActiveProvider { get; set; } public new RelationalTestStore TestStore => (RelationalTestStore)base.TestStore; @@ -601,7 +599,7 @@ public class EmptyMigrationsContext(DbContextOptions options) : DbContext(option public class MigrationsContext(DbContextOptions options) : PoolableDbContext(options) { - public DbSet Foos { get; set; } + public DbSet Foos { get; set; } = null!; } protected override void OnModelCreating(ModelBuilder modelBuilder, DbContext context) @@ -629,7 +627,7 @@ public class Foo { public int Id { get; set; } public int Bar { get; set; } - public string Description { get; set; } + public string? Description { get; set; } } [DbContext(typeof(MigrationsContext)), Migration("00000000000001_Migration1")] diff --git a/test/EFCore.Relational.Specification.Tests/Migrations/MigrationsSqlGeneratorTestBase.cs b/test/EFCore.Relational.Specification.Tests/Migrations/MigrationsSqlGeneratorTestBase.cs index 02ae4085fa6..68bb27411e3 100644 --- a/test/EFCore.Relational.Specification.Tests/Migrations/MigrationsSqlGeneratorTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/Migrations/MigrationsSqlGeneratorTestBase.cs @@ -6,17 +6,15 @@ namespace Microsoft.EntityFrameworkCore.Migrations; -#nullable disable - public abstract class MigrationsSqlGeneratorTestBase( TestHelpers testHelpers, - IServiceCollection customServices = null, - DbContextOptions options = null) + IServiceCollection? customServices = null, + DbContextOptions? options = null) { protected static string EOL => Environment.NewLine; - protected virtual string Sql { get; set; } + protected virtual string Sql { get; set; } = null!; [Fact] public void All_tests_must_be_overriden() @@ -226,13 +224,13 @@ public virtual void InsertDataOperation_all_args_spatial() ColumnTypes = ["int", "varchar(40)", GetGeometryCollectionStoreType()], Values = new object[,] { - { 0, null, null }, - { 1, "Daenerys Targaryen", null }, - { 2, "John Snow", null }, - { 3, "Arya Stark", null }, - { 4, "Harry Strickland", null }, - { 5, "The Imp", null }, - { 6, "The Kingslayer", null }, + { 0, null!, null! }, + { 1, "Daenerys Targaryen", null! }, + { 2, "John Snow", null! }, + { 3, "Arya Stark", null! }, + { 4, "Harry Strickland", null! }, + { 5, "The Imp", null! }, + { 6, "The Kingslayer", null! }, { 7, "Aemon Targaryen", _geometryCollection } } }); @@ -298,7 +296,7 @@ public virtual void InsertDataOperation_throws_for_unsupported_column_types() Schema = "dbo", Columns = ["First Name"], ColumnTypes = ["char[]"], - Values = new object[,] { { null } } + Values = new object[,] { { null! } } })).Message); [Fact] @@ -379,7 +377,7 @@ public virtual void DeleteDataOperation_all_args_composite() KeyColumns = ["First Name", "Last Name"], KeyValues = new object[,] { - { "Hodor", null }, { "Daenerys", "Targaryen" }, { "John", "Snow" }, { "Arya", "Stark" }, { "Harry", "Strickland" } + { "Hodor", null! }, { "Daenerys", "Targaryen" }, { "John", "Snow" }, { "Arya", "Stark" }, { "Harry", "Strickland" } } }); @@ -467,7 +465,7 @@ public virtual void UpdateDataOperation_all_args_composite() { Table = "People", KeyColumns = ["First Name", "Last Name"], - KeyValues = new object[,] { { "Hodor", null }, { "Daenerys", "Targaryen" } }, + KeyValues = new object[,] { { "Hodor", null! }, { "Daenerys", "Targaryen" } }, Columns = ["House Allegiance"], Values = new object[,] { { "Stark" }, { "Targaryen" } } }); @@ -480,7 +478,7 @@ public virtual void UpdateDataOperation_all_args_composite_multi() { Table = "People", KeyColumns = ["First Name", "Last Name"], - KeyValues = new object[,] { { "Hodor", null }, { "Daenerys", "Targaryen" } }, + KeyValues = new object[,] { { "Hodor", null! }, { "Daenerys", "Targaryen" } }, Columns = ["Birthplace", "House Allegiance", "Culture"], Values = new object[,] { { "Winterfell", "Stark", "Northmen" }, { "Dragonstone", "Targaryen", "Valyrian" } } }); @@ -731,8 +729,8 @@ private static void CreateGotModel(ModelBuilder b) }); protected TestHelpers TestHelpers { get; } = testHelpers; - protected DbContextOptions ContextOptions { get; } = options; - protected IServiceCollection CustomServices { get; } = customServices; + protected DbContextOptions? ContextOptions { get; } = options; + protected IServiceCollection? CustomServices { get; } = customServices; protected virtual void Generate(MigrationOperation operation, MigrationsSqlGenerationOptions options) => Generate(null, [operation], options); @@ -741,7 +739,7 @@ protected virtual void Generate(params MigrationOperation[] operation) => Generate(null, operation); protected virtual void Generate( - Action buildAction, + Action? buildAction, Action migrateAction, MigrationsSqlGenerationOptions options = MigrationsSqlGenerationOptions.Default) { @@ -751,19 +749,19 @@ protected virtual void Generate( Generate(buildAction, migrationBuilder.Operations.ToArray(), options); } - protected virtual void Generate(Action buildAction, params MigrationOperation[] operation) + protected virtual void Generate(Action? buildAction, params MigrationOperation[] operation) => Generate(buildAction, operation, MigrationsSqlGenerationOptions.Default); protected virtual void Generate( - Action buildAction, + Action? buildAction, MigrationOperation[] operation, MigrationsSqlGenerationOptions options) { var services = ContextOptions != null - ? TestHelpers.CreateContextServices(CustomServices, ContextOptions) - : TestHelpers.CreateContextServices(CustomServices); + ? TestHelpers.CreateContextServices(CustomServices!, ContextOptions) + : TestHelpers.CreateContextServices(CustomServices!); - IModel model = null; + IModel? model = null; if (buildAction != null) { var modelBuilder = TestHelpers.CreateConventionBuilder(services); @@ -786,7 +784,7 @@ protected void AssertSql(string expected) protected class Person { public int Id { get; set; } - public string Name { get; set; } + public string? Name { get; set; } public decimal Pi { get; set; } } } diff --git a/test/EFCore.Relational.Specification.Tests/Migrations/MigrationsTestBase.cs b/test/EFCore.Relational.Specification.Tests/Migrations/MigrationsTestBase.cs index 54b468d0a11..7b065185e94 100644 --- a/test/EFCore.Relational.Specification.Tests/Migrations/MigrationsTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/Migrations/MigrationsTestBase.cs @@ -7,8 +7,6 @@ namespace Microsoft.EntityFrameworkCore.Migrations; -#nullable disable - public abstract class MigrationsTestBase : IClassFixture where TFixture : MigrationsTestBase.MigrationsFixtureBase, new() { @@ -20,8 +18,8 @@ public abstract class MigrationsTestBase : IClassFixture protected MigrationsTestBase(TFixture fixture) { Fixture = fixture; - _sqlGenerationHelper = Fixture.ServiceProvider.GetService(); - _typeMappingSource = Fixture.ServiceProvider.GetService(); + _sqlGenerationHelper = Fixture.ServiceProvider.GetRequiredService(); + _typeMappingSource = Fixture.ServiceProvider.GetRequiredService(); } [Fact] @@ -50,8 +48,8 @@ public virtual Task Create_table() [Fact] public virtual async Task Create_table_all_settings() { - var intStoreType = TypeMappingSource.FindMapping(typeof(int)).StoreType; - var char11StoreType = TypeMappingSource.FindMapping(typeof(string), storeTypeName: null, size: 11).StoreType; + var intStoreType = TypeMappingSource.FindMapping(typeof(int))!.StoreType; + var char11StoreType = TypeMappingSource.FindMapping(typeof(string), storeTypeName: null, size: 11)!.StoreType; await Test( builder => builder.Entity( @@ -726,7 +724,7 @@ public virtual async Task Add_column_with_defaultValue_unspecified() protected class Owner { public int Id { get; set; } - public Owned Owned { get; set; } + public Owned? Owned { get; set; } } protected class Owned @@ -856,7 +854,7 @@ public virtual Task Add_column_with_required() { var table = Assert.Single(model.Tables); var column = Assert.Single(table.Columns, c => c.Name == "Name"); - Assert.Equal(TypeMappingSource.FindMapping(typeof(string)).StoreType, column.StoreType); + Assert.Equal(TypeMappingSource.FindMapping(typeof(string))!.StoreType, column.StoreType); Assert.False(column.IsNullable); }); @@ -872,7 +870,7 @@ public virtual Task Add_column_with_ansi() var column = Assert.Single(table.Columns, c => c.Name == "Name"); Assert.Equal( TypeMappingSource - .FindMapping(typeof(string), storeTypeName: null, unicode: false) + .FindMapping(typeof(string), storeTypeName: null, unicode: false)! .StoreType, column.StoreType); Assert.True(column.IsNullable); }); @@ -889,7 +887,7 @@ public virtual Task Add_column_with_max_length() var column = Assert.Single(table.Columns, c => c.Name == "Name"); Assert.Equal( TypeMappingSource - .FindMapping(typeof(string), storeTypeName: null, size: 30) + .FindMapping(typeof(string), storeTypeName: null, size: 30)! .StoreType, column.StoreType); }); @@ -906,7 +904,7 @@ public virtual Task Add_column_with_unbounded_max_length() var column = Assert.Single(table.Columns, c => c.Name == "Name"); Assert.Equal( TypeMappingSource - .FindMapping(typeof(string), storeTypeName: null, size: -1) + .FindMapping(typeof(string), storeTypeName: null, size: -1)! .StoreType, column.StoreType); }); @@ -934,7 +932,7 @@ public virtual Task Add_column_with_max_length_on_derived() var column = Assert.Single(table.Columns, c => c.Name == "Name"); Assert.Equal( TypeMappingSource - .FindMapping(typeof(string), storeTypeName: null, size: 30) + .FindMapping(typeof(string), storeTypeName: null, size: 30)! .StoreType, column.StoreType); }); @@ -953,7 +951,7 @@ public virtual Task Add_column_with_fixed_length() var column = Assert.Single(table.Columns, c => c.Name == "Name"); Assert.Equal( TypeMappingSource - .FindMapping(typeof(string), storeTypeName: null, fixedLength: true, size: 100) + .FindMapping(typeof(string), storeTypeName: null, fixedLength: true, size: 100)! .StoreType, column.StoreType); }); @@ -1060,7 +1058,7 @@ public virtual Task Alter_column_change_type() { var table = Assert.Single(model.Tables); var column = Assert.Single(table.Columns, c => c.Name == "SomeColumn"); - Assert.Equal(_typeMappingSource.FindMapping(typeof(long)).StoreType, column.StoreType); + Assert.Equal(_typeMappingSource.FindMapping(typeof(long))!.StoreType, column.StoreType); }); [Fact] @@ -1089,7 +1087,7 @@ public virtual Task Alter_column_make_required_with_null_data() { e.Property("Id"); e.Property("SomeColumn"); - e.HasData(new Dictionary { { "Id", 1 }, { "SomeColumn", null } }); + e.HasData(new Dictionary { { "Id", 1 }, { "SomeColumn", null } }); }), builder => { }, builder => builder.Entity("People").Property("SomeColumn").IsRequired(), @@ -1391,7 +1389,7 @@ public virtual async Task Convert_owned_entity_with_no_schema_to_regular_entity( "Owned", "OwnedReference", o => { o.Property("Date"); - o.ToTable("Owned", (string)null); + o.ToTable("Owned", (string?)null); })), target => target.Entity( "Owned", e => @@ -1399,7 +1397,7 @@ public virtual async Task Convert_owned_entity_with_no_schema_to_regular_entity( e.Property("EntityId").ValueGeneratedNever(); e.HasKey("EntityId"); e.Property("Date"); - e.ToTable("Owned", (string)null); + e.ToTable("Owned", (string?)null); }), model => { @@ -2804,10 +2802,10 @@ public virtual Task Create_table_with_optional_complex_type_with_required_proper protected class MyComplex { [Required] - public string Prop { get; set; } + public string Prop { get; set; } = null!; - public MyNestedComplex Nested { get; set; } - public List NestedCollection { get; set; } + public MyNestedComplex Nested { get; set; } = null!; + public List NestedCollection { get; set; } = []; } public class MyNestedComplex @@ -3407,16 +3405,16 @@ public virtual Task Multiop_rename_table_and_create_new_table_with_the_old_name( protected class MyJsonComplex { - public string Value { get; set; } + public string? Value { get; set; } public DateTime Date { get; set; } - public MyNestedComplex Nested { get; set; } - public List NestedCollection { get; set; } + public MyNestedComplex Nested { get; set; } = null!; + public List NestedCollection { get; set; } = []; } protected class Person { public int Id { get; set; } - public string Name { get; set; } + public string? Name { get; set; } public int AnotherId { get; set; } public int Age { get; set; } } @@ -3457,7 +3455,7 @@ protected virtual IRelationalTypeMappingSource TypeMappingSource protected virtual Task Test( Action buildSourceAction, Action buildTargetAction, - Action asserter, + Action? asserter, bool withConventions = true, MigrationsSqlGenerationOptions migrationsSqlGenerationOptions = MigrationsSqlGenerationOptions.Default) => Test(_ => { }, buildSourceAction, buildTargetAction, asserter, withConventions, migrationsSqlGenerationOptions); @@ -3503,7 +3501,7 @@ protected virtual Task Test( Action buildCommonAction, Action buildSourceAction, Action buildTargetAction, - Action asserter, + Action? asserter, bool withConventions = true, MigrationsSqlGenerationOptions migrationsSqlGenerationOptions = MigrationsSqlGenerationOptions.Default) { @@ -3577,9 +3575,9 @@ protected virtual Task Test( protected virtual async Task Test( IModel sourceModel, - IModel targetModel, + IModel? targetModel, IReadOnlyList operations, - Action asserter, + Action? asserter, MigrationsSqlGenerationOptions migrationsSqlGenerationOptions = MigrationsSqlGenerationOptions.Default) { var context = CreateContext(); @@ -3669,14 +3667,14 @@ protected IModel BuildModelFromSnapshotSource(string code) } var assembly = build.BuildInMemory(); - var factoryType = assembly.GetType("MigrationsTestSnapshot"); + var factoryType = assembly.GetType("MigrationsTestSnapshot")!; var buildModelMethod = factoryType.GetMethod( "BuildModel", BindingFlags.Instance | BindingFlags.NonPublic, null, [typeof(ModelBuilder)], - null); + null)!; var builder = new ModelBuilder(); builder.Model.RemoveAnnotation(CoreAnnotationNames.ProductVersion); @@ -3686,8 +3684,8 @@ protected IModel BuildModelFromSnapshotSource(string code) [builder]); var services = Fixture.TestHelpers.CreateContextServices(); - var processor = new SnapshotModelProcessor(new TestOperationReporter(), services.GetService()); - return processor.Process(builder.Model); + var processor = new SnapshotModelProcessor(new TestOperationReporter(), services.GetRequiredService()); + return processor.Process(builder.Model)!; } protected virtual ICollection GetAdditionalReferences() diff --git a/test/EFCore.Relational.Specification.Tests/ModelBuilding101TestBase.cs b/test/EFCore.Relational.Specification.Tests/ModelBuilding101TestBase.cs index 2967ad6cef8..69ed5446eb8 100644 --- a/test/EFCore.Relational.Specification.Tests/ModelBuilding101TestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/ModelBuilding101TestBase.cs @@ -3,8 +3,6 @@ namespace Microsoft.EntityFrameworkCore; -#nullable disable - public abstract class ModelBuilding101RelationalTestBase : ModelBuilding101TestBase { protected override ModelMetadata GetModelMetadata(Context101 context) diff --git a/test/EFCore.Relational.Specification.Tests/OptimisticConcurrencyRelationalTestBase.cs b/test/EFCore.Relational.Specification.Tests/OptimisticConcurrencyRelationalTestBase.cs index f9b38429512..251bb9cc40f 100644 --- a/test/EFCore.Relational.Specification.Tests/OptimisticConcurrencyRelationalTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/OptimisticConcurrencyRelationalTestBase.cs @@ -6,8 +6,6 @@ // ReSharper disable InconsistentNaming namespace Microsoft.EntityFrameworkCore; -#nullable disable - public abstract class OptimisticConcurrencyRelationalTestBase(TFixture fixture) : OptimisticConcurrencyTestBase(fixture) where TFixture : F1RelationalFixture, new() diff --git a/test/EFCore.Relational.Specification.Tests/PropertyValuesRelationalTestBase.cs b/test/EFCore.Relational.Specification.Tests/PropertyValuesRelationalTestBase.cs index 54876947703..ec283063b9e 100644 --- a/test/EFCore.Relational.Specification.Tests/PropertyValuesRelationalTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/PropertyValuesRelationalTestBase.cs @@ -3,8 +3,6 @@ namespace Microsoft.EntityFrameworkCore; -#nullable disable - public abstract class PropertyValuesRelationalTestBase(TFixture fixture) : PropertyValuesTestBase(fixture) where TFixture : PropertyValuesRelationalTestBase.PropertyValuesRelationalFixture, new() diff --git a/test/EFCore.Relational.Specification.Tests/Query/AdHocAdvancedMappingsQueryRelationalTestBase.cs b/test/EFCore.Relational.Specification.Tests/Query/AdHocAdvancedMappingsQueryRelationalTestBase.cs index 16252a11348..4d5abd442be 100644 --- a/test/EFCore.Relational.Specification.Tests/Query/AdHocAdvancedMappingsQueryRelationalTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/Query/AdHocAdvancedMappingsQueryRelationalTestBase.cs @@ -3,8 +3,6 @@ namespace Microsoft.EntityFrameworkCore.Query; -#nullable disable - public abstract class AdHocAdvancedMappingsQueryRelationalTestBase(NonSharedFixture fixture) : AdHocAdvancedMappingsQueryTestBase(fixture) { protected TestSqlLoggerFactory TestSqlLoggerFactory @@ -33,8 +31,8 @@ public virtual async Task Two_similar_complex_properties_projected_with_split_qu var resultElement = query.Single(); foreach (var variation in resultElement.Variations) { - Assert.NotEqual(variation.Payment.Brutto, variation.Nested.Payment.Brutto); - Assert.NotEqual(variation.Payment.Netto, variation.Nested.Payment.Netto); + Assert.NotEqual(variation.Payment.Brutto, variation.Nested!.Payment.Brutto); + Assert.NotEqual(variation.Payment.Netto, variation.Nested!.Payment.Netto); } } @@ -52,8 +50,8 @@ public virtual async Task Two_similar_complex_properties_projected_with_split_qu foreach (var variation in query.Variations) { - Assert.NotEqual(variation.Payment.Brutto, variation.Nested.Payment.Brutto); - Assert.NotEqual(variation.Payment.Netto, variation.Nested.Payment.Netto); + Assert.NotEqual(variation.Payment.Brutto, variation.Nested!.Payment.Brutto); + Assert.NotEqual(variation.Payment.Netto, variation.Nested!.Payment.Netto); } } @@ -65,7 +63,7 @@ public virtual async Task Projecting_one_of_two_similar_complex_types_picks_the_ using var context = contextFactory.CreateDbContext(); var query = context.Cs - .Where(x => x.B.AId.Value == 1) + .Where(x => x.B.AId!.Value == 1) .OrderBy(x => x.Id) .Take(10) .Select(x => new @@ -79,7 +77,7 @@ public virtual async Task Projecting_one_of_two_similar_complex_types_picks_the_ protected class Context32911(DbContextOptions options) : DbContext(options) { - public DbSet Offers { get; set; } + public DbSet Offers { get; set; } = null!; protected override void OnModelCreating(ModelBuilder modelBuilder) { @@ -147,14 +145,14 @@ public abstract class EntityBase public class Offer : EntityBase { - public ICollection Variations { get; set; } + public ICollection Variations { get; set; } = null!; } public class Variation : EntityBase { public Payment Payment { get; set; } = new(0, 0); - public NestedEntity Nested { get; set; } + public NestedEntity? Nested { get; set; } } public class NestedEntity : EntityBase @@ -167,9 +165,9 @@ public record Payment(double Netto, double Brutto); protected class Context32911_2(DbContextOptions options) : DbContext(options) { - public DbSet As { get; set; } - public DbSet Bs { get; set; } - public DbSet Cs { get; set; } + public DbSet As { get; set; } = null!; + public DbSet Bs { get; set; } = null!; + public DbSet Cs { get; set; } = null!; protected override void OnModelCreating(ModelBuilder modelBuilder) { @@ -212,19 +210,19 @@ public class A public class B { public int Id { get; set; } - public Metadata Info { get; set; } + public Metadata Info { get; set; } = null!; public int? AId { get; set; } - public A A { get; set; } + public A A { get; set; } = null!; } public class C { public int Id { get; set; } - public Metadata Info { get; set; } + public Metadata Info { get; set; } = null!; public int BId { get; set; } - public B B { get; set; } + public B B { get; set; } = null!; } } @@ -326,7 +324,7 @@ public abstract class BaseEntity public class ReproEntity : BaseEntity { - public T Value { get; set; } + public T Value { get; set; } = default!; } } diff --git a/test/EFCore.Relational.Specification.Tests/Query/AdHocMiscellaneousQueryRelationalTestBase.cs b/test/EFCore.Relational.Specification.Tests/Query/AdHocMiscellaneousQueryRelationalTestBase.cs index 47bfb9a116b..522541a25a4 100644 --- a/test/EFCore.Relational.Specification.Tests/Query/AdHocMiscellaneousQueryRelationalTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/Query/AdHocMiscellaneousQueryRelationalTestBase.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable disable - using System.ComponentModel.DataAnnotations.Schema; using System.Text.Json; using NameSpace1; @@ -48,7 +46,7 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) => modelBuilder.Entity().ToTable("ZeroKey", t => t.ExcludeFromMigrations()) .Property(z => z.Id).ValueGeneratedNever(); - public DbSet ZeroKeys { get; set; } + public DbSet ZeroKeys { get; set; } = null!; public class ZeroKey2951 { @@ -138,20 +136,20 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) public class Entity11818 { public int Id { get; set; } - public string Name { get; set; } + public string? Name { get; set; } } public class AnotherEntity11818 { public int Id { get; set; } - public string Name { get; set; } + public string? Name { get; set; } public bool Exists { get; set; } } public class MaumarEntity11818 { public int Id { get; set; } - public string Name { get; set; } + public string? Name { get; set; } public bool Exists { get; set; } } } @@ -176,15 +174,15 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) { var mb = modelBuilder.Entity(typeof(TestQuery)); - mb.HasBaseType((Type)null); + mb.HasBaseType((Type)null!); mb.HasNoKey(); - mb.ToTable((string)null); + mb.ToTable((string)null!); mb = modelBuilder.Entity(typeof(NameSpace2.TestQuery)); - mb.HasBaseType((Type)null); + mb.HasBaseType((Type)null!); mb.HasNoKey(); - mb.ToTable((string)null); + mb.ToTable((string)null!); } } @@ -216,11 +214,11 @@ public virtual async Task StoreType_for_UDF_used(bool async) protected class Context27954(DbContextOptions options) : DbContext(options) { - public DbSet MyEntities { get; set; } + public DbSet MyEntities { get; set; } = null!; protected override void OnModelCreating(ModelBuilder modelBuilder) => modelBuilder - .HasDbFunction(typeof(MyEntity).GetMethod(nameof(MyEntity.Modify))) + .HasDbFunction(typeof(MyEntity).GetMethod(nameof(MyEntity.Modify))!) .HasName("ModifyDate") .HasStoreType("datetime") .HasSchema("dbo"); @@ -253,7 +251,7 @@ public virtual async Task Mapping_JsonElement_property_throws_a_meaningful_excep protected class Context34752(DbContextOptions options) : DbContext(options) { - public DbSet Entities { get; set; } + public DbSet Entities { get; set; } = null!; public class Entity { @@ -299,12 +297,12 @@ public virtual async Task Check_inlined_constants_redacting(bool async, bool ena protected class InlinedRedactingContext(DbContextOptions options) : DbContext(options) { - public DbSet TestEntities { get; set; } + public DbSet TestEntities { get; set; } = null!; public class TestEntity { public int Id { get; set; } - public string Name { get; set; } + public string Name { get; set; } = null!; } } @@ -322,7 +320,7 @@ public virtual async Task Entity_equality_with_Contains_and_Parameter(bool async using var context = contextFactory.CreateDbContext(); List details = [new() { Id = 1 }, new() { Id = 2 }]; - var query = context.Blogs.Where(b => details.Contains(b.Details)); + var query = context.Blogs.Where(b => details.Contains(b.Details!)); var result = async ? await query.ToListAsync() @@ -331,20 +329,20 @@ public virtual async Task Entity_equality_with_Contains_and_Parameter(bool async protected class Context36311(DbContextOptions options) : DbContext(options) { - public DbSet Blogs { get; set; } + public DbSet Blogs { get; set; } = null!; public class Blog { public int Id { get; set; } - public string Name { get; set; } + public string? Name { get; set; } - public BlogDetails Details { get; set; } + public BlogDetails? Details { get; set; } } public class BlogDetails { public int Id { get; set; } - public string Name { get; set; } + public string? Name { get; set; } } } @@ -376,7 +374,7 @@ public virtual async Task Like_on_value_converted_string_column_does_not_produce protected class Context36247(DbContextOptions options) : DbContext(options) { - public DbSet Users { get; set; } + public DbSet Users { get; set; } = null!; protected override void OnModelCreating(ModelBuilder modelBuilder) => modelBuilder.Entity().Property(e => e.Name) @@ -456,8 +454,8 @@ orderby s.PickupStatusId // status 1 -> matched, Count 2 Assert.Equal(1, result[0].PickupStatusId); Assert.NotNull(result[0].countInfo); - Assert.Equal(1, result[0].countInfo.pickupStatusId); - Assert.Equal(2, result[0].countInfo.Count); + Assert.Equal(1, result[0].countInfo!.pickupStatusId); + Assert.Equal(2, result[0].countInfo!.Count); // status 2 -> no match, whole non-entity object is null Assert.Equal(2, result[1].PickupStatusId); @@ -466,8 +464,8 @@ orderby s.PickupStatusId // status 3 -> matched, Count 1 Assert.Equal(3, result[2].PickupStatusId); Assert.NotNull(result[2].countInfo); - Assert.Equal(3, result[2].countInfo.pickupStatusId); - Assert.Equal(1, result[2].countInfo.Count); + Assert.Equal(3, result[2].countInfo!.pickupStatusId); + Assert.Equal(1, result[2].countInfo!.Count); } [Fact] @@ -490,8 +488,8 @@ public virtual async Task Anon_whole_object_LeftJoin_operator() // status 1 -> matched, Count 2 Assert.Equal(1, result[0].PickupStatusId); Assert.NotNull(result[0].countInfo); - Assert.Equal(1, result[0].countInfo.pickupStatusId); - Assert.Equal(2, result[0].countInfo.Count); + Assert.Equal(1, result[0].countInfo!.pickupStatusId); + Assert.Equal(2, result[0].countInfo!.Count); // status 2 -> no match, whole non-entity object is null Assert.Equal(2, result[1].PickupStatusId); @@ -500,8 +498,8 @@ public virtual async Task Anon_whole_object_LeftJoin_operator() // status 3 -> matched, Count 1 Assert.Equal(3, result[2].PickupStatusId); Assert.NotNull(result[2].countInfo); - Assert.Equal(3, result[2].countInfo.pickupStatusId); - Assert.Equal(1, result[2].countInfo.Count); + Assert.Equal(3, result[2].countInfo!.pickupStatusId); + Assert.Equal(1, result[2].countInfo!.Count); } [Fact] @@ -595,8 +593,8 @@ public virtual async Task Dto_memberinit_whole_object_LeftJoin() // status 1 -> matched, Count 2 Assert.Equal(1, result[0].PickupStatusId); Assert.NotNull(result[0].countInfo); - Assert.Equal(1, result[0].countInfo.PickupStatusId); - Assert.Equal(2, result[0].countInfo.Count); + Assert.Equal(1, result[0].countInfo!.PickupStatusId); + Assert.Equal(2, result[0].countInfo!.Count); // status 2 -> no match, whole DTO object is null Assert.Equal(2, result[1].PickupStatusId); @@ -605,8 +603,8 @@ public virtual async Task Dto_memberinit_whole_object_LeftJoin() // status 3 -> matched, Count 1 Assert.Equal(3, result[2].PickupStatusId); Assert.NotNull(result[2].countInfo); - Assert.Equal(3, result[2].countInfo.PickupStatusId); - Assert.Equal(1, result[2].countInfo.Count); + Assert.Equal(3, result[2].countInfo!.PickupStatusId); + Assert.Equal(1, result[2].countInfo!.Count); } [Fact] @@ -787,8 +785,8 @@ from countInfo in g.DefaultIfEmpty() // status 1 -> matched, Count 2 Assert.Equal(1, result[0].key); Assert.NotNull(result[0].anyInfo); - Assert.Equal(1, result[0].anyInfo.pickupStatusId); - Assert.Equal(2, result[0].anyInfo.Count); + Assert.Equal(1, result[0].anyInfo!.pickupStatusId); + Assert.Equal(2, result[0].anyInfo!.Count); // status 2 -> no match on the left join; whole non-entity object is null after grouping Assert.Equal(2, result[1].key); @@ -797,8 +795,8 @@ from countInfo in g.DefaultIfEmpty() // status 3 -> matched, Count 1 Assert.Equal(3, result[2].key); Assert.NotNull(result[2].anyInfo); - Assert.Equal(3, result[2].anyInfo.pickupStatusId); - Assert.Equal(1, result[2].anyInfo.Count); + Assert.Equal(3, result[2].anyInfo!.pickupStatusId); + Assert.Equal(1, result[2].anyInfo!.Count); } [Fact] @@ -826,7 +824,7 @@ from countInfo in g.DefaultIfEmpty() Assert.Equal(1, result[0].key); Assert.NotNull(result[0].wrapper); Assert.NotNull(result[0].wrapper.anyInfo); - Assert.Equal(2, result[0].wrapper.anyInfo.Count); + Assert.Equal(2, result[0].wrapper.anyInfo!.Count); Assert.Equal(2, result[1].key); Assert.NotNull(result[1].wrapper); @@ -835,7 +833,7 @@ from countInfo in g.DefaultIfEmpty() Assert.Equal(3, result[2].key); Assert.NotNull(result[2].wrapper); Assert.NotNull(result[2].wrapper.anyInfo); - Assert.Equal(1, result[2].wrapper.anyInfo.Count); + Assert.Equal(1, result[2].wrapper.anyInfo!.Count); } [Fact] @@ -865,8 +863,8 @@ from countInfo in g.DefaultIfEmpty() // status 1 -> matched, Count 2 Assert.Equal(1, result[0].key); Assert.NotNull(result[0].anyInfo); - Assert.Equal(1, result[0].anyInfo.PickupStatusId); - Assert.Equal(2, result[0].anyInfo.Count); + Assert.Equal(1, result[0].anyInfo!.PickupStatusId); + Assert.Equal(2, result[0].anyInfo!.Count); // status 2 -> no match on the left join; whole DTO object is null after grouping Assert.Equal(2, result[1].key); @@ -875,8 +873,8 @@ from countInfo in g.DefaultIfEmpty() // status 3 -> matched, Count 1 Assert.Equal(3, result[2].key); Assert.NotNull(result[2].anyInfo); - Assert.Equal(3, result[2].anyInfo.PickupStatusId); - Assert.Equal(1, result[2].anyInfo.Count); + Assert.Equal(3, result[2].anyInfo!.PickupStatusId); + Assert.Equal(1, result[2].anyInfo!.Count); } [Fact] @@ -1484,11 +1482,11 @@ public virtual async Task Two_left_joined_nonentity_objects_second_marker_orphan // status 1 -> both joins matched, Count 2 Assert.Equal(1, result[0].PickupStatusId); Assert.NotNull(result[0].first); - Assert.Equal(1, result[0].first.pickupStatusId); - Assert.Equal(2, result[0].first.Count); + Assert.Equal(1, result[0].first!.pickupStatusId); + Assert.Equal(2, result[0].first!.Count); Assert.NotNull(result[0].second); - Assert.Equal(1, result[0].second.pickupStatusId); - Assert.Equal(2, result[0].second.Count); + Assert.Equal(1, result[0].second!.pickupStatusId); + Assert.Equal(2, result[0].second!.Count); // status 2 -> neither join matched; both whole non-entity objects are null. // The first object's marker passes through the second join's outer-shaper remap, @@ -1500,11 +1498,11 @@ public virtual async Task Two_left_joined_nonentity_objects_second_marker_orphan // status 3 -> both joins matched, Count 1 Assert.Equal(3, result[2].PickupStatusId); Assert.NotNull(result[2].first); - Assert.Equal(3, result[2].first.pickupStatusId); - Assert.Equal(1, result[2].first.Count); + Assert.Equal(3, result[2].first!.pickupStatusId); + Assert.Equal(1, result[2].first!.Count); Assert.NotNull(result[2].second); - Assert.Equal(3, result[2].second.pickupStatusId); - Assert.Equal(1, result[2].second.Count); + Assert.Equal(3, result[2].second!.pickupStatusId); + Assert.Equal(1, result[2].second!.Count); } [Fact] @@ -1785,23 +1783,23 @@ public virtual async Task Nested_transparent_identifier_of_entities_as_leftjoin_ // status 1 -> two matched rows, each with a pair whose entities reference status 1 Assert.Equal(1, result[0].PickupStatusId); Assert.NotNull(result[0].pair); - Assert.Equal(1, result[0].pair.s2.PickupStatusId); + Assert.Equal(1, result[0].pair!.s2!.PickupStatusId); Assert.Equal(1, result[1].PickupStatusId); Assert.NotNull(result[1].pair); - Assert.Equal(1, result[1].pair.s2.PickupStatusId); + Assert.Equal(1, result[1].pair!.s2!.PickupStatusId); // status 2 -> no match. The inner shaper is a transparent-identifier { r, s2 } whose decomposed // members are entities; the wrapper itself materializes (non-null) with both entity members null, // rather than the whole pair being nulled (the pair is not a single user-projected non-entity object). Assert.Equal(2, result[2].PickupStatusId); Assert.NotNull(result[2].pair); - Assert.Null(result[2].pair.r); - Assert.Null(result[2].pair.s2); + Assert.Null(result[2].pair!.r); + Assert.Null(result[2].pair!.s2); // status 3 -> matched Assert.Equal(3, result[3].PickupStatusId); Assert.NotNull(result[3].pair); - Assert.Equal(3, result[3].pair.s2.PickupStatusId); + Assert.Equal(3, result[3].pair!.s2!.PickupStatusId); } [Fact] @@ -1979,8 +1977,8 @@ private static async Task Seed30915MatchedZeroAggregate(Context30915 context) protected class Context30915(DbContextOptions options) : DbContext(options) { - public DbSet Statuses { get; set; } - public DbSet Requests { get; set; } + public DbSet Statuses { get; set; } = null!; + public DbSet Requests { get; set; } = null!; protected override void OnModelCreating(ModelBuilder modelBuilder) => modelBuilder.Entity(b => @@ -1992,7 +1990,7 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) public class PickupStatus30915 { public int PickupStatusId { get; set; } - public string Name { get; set; } + public string Name { get; set; } = null!; } public class PickupRequest30915 diff --git a/test/EFCore.Relational.Specification.Tests/Query/AdHocNavigationsQueryRelationalTestBase.cs b/test/EFCore.Relational.Specification.Tests/Query/AdHocNavigationsQueryRelationalTestBase.cs index 6347c46571f..33d3c57900b 100644 --- a/test/EFCore.Relational.Specification.Tests/Query/AdHocNavigationsQueryRelationalTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/Query/AdHocNavigationsQueryRelationalTestBase.cs @@ -3,8 +3,6 @@ namespace Microsoft.EntityFrameworkCore.Query; -#nullable disable - public abstract class AdHocNavigationsQueryRelationalTestBase(NonSharedFixture fixture) : AdHocNavigationsQueryTestBase(fixture) { protected TestSqlLoggerFactory TestSqlLoggerFactory @@ -43,7 +41,7 @@ public virtual async Task Select_enumerable_navigation_backed_by_collection(bool // Protected so that it can be used by inheriting tests, and so that things like unused setters are not removed. protected class Context21803(DbContextOptions options) : DbContext(options) { - public DbSet Entities { get; set; } + public DbSet Entities { get; set; } = null!; public async Task SeedAsync() { @@ -70,7 +68,7 @@ public IEnumerable OtherEntities public class OtherEntity { public int Id { get; private set; } - public AppEntity AppEntity { get; set; } + public AppEntity AppEntity { get; set; } = null!; } } @@ -153,7 +151,7 @@ public virtual async Task Consecutive_selects_with_conditional_projection_nested protected class ContextConditionalProjection(DbContextOptions options) : DbContext(options) { - public DbSet Users { get; set; } + public DbSet Users { get; set; } = null!; public async Task SeedAsync() { @@ -176,20 +174,20 @@ public class User { public long Id { get; set; } public long? JobId { get; set; } - public Job Job { get; set; } + public Job? Job { get; set; } } public class Job { public long Id { get; set; } public long AddressId { get; set; } - public Address Address { get; set; } + public Address Address { get; set; } = null!; } public class Address { public long Id { get; set; } - public string Street { get; set; } + public string Street { get; set; } = null!; } } diff --git a/test/EFCore.Relational.Specification.Tests/Query/AdHocQueryFiltersQueryRelationalTestBase.cs b/test/EFCore.Relational.Specification.Tests/Query/AdHocQueryFiltersQueryRelationalTestBase.cs index 2e3389bee75..68072cb7bc2 100644 --- a/test/EFCore.Relational.Specification.Tests/Query/AdHocQueryFiltersQueryRelationalTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/Query/AdHocQueryFiltersQueryRelationalTestBase.cs @@ -3,8 +3,6 @@ namespace Microsoft.EntityFrameworkCore.Query; -#nullable disable - public abstract class AdHocQueryFiltersQueryRelationalTestBase(NonSharedFixture fixture) : AdHocQueryFiltersQueryTestBase(fixture) { protected TestSqlLoggerFactory TestSqlLoggerFactory diff --git a/test/EFCore.Relational.Specification.Tests/Query/AdHocQuerySplittingQueryTestBase.cs b/test/EFCore.Relational.Specification.Tests/Query/AdHocQuerySplittingQueryTestBase.cs index 1ecda88f408..228dfae6c3a 100644 --- a/test/EFCore.Relational.Specification.Tests/Query/AdHocQuerySplittingQueryTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/Query/AdHocQuerySplittingQueryTestBase.cs @@ -6,8 +6,6 @@ namespace Microsoft.EntityFrameworkCore.Query; -#nullable disable - public abstract class AdHocQuerySplittingQueryTestBase(NonSharedFixture fixture) : NonSharedModelTestBase(fixture), IClassFixture { @@ -145,7 +143,7 @@ public virtual async Task SplitQuery_disposes_inner_data_readers() protected class Context21355(DbContextOptions options) : DbContext(options) { - public DbSet Parents { get; set; } + public DbSet Parents { get; set; } = null!; public async Task SeedAsync() { @@ -155,23 +153,23 @@ public async Task SeedAsync() public class Parent { - public string Id { get; set; } - public List Children1 { get; set; } - public List Children2 { get; set; } + public string Id { get; set; } = null!; + public List Children1 { get; set; } = null!; + public List Children2 { get; set; } = null!; } public class Child { public int Id { get; set; } - public string ParentId { get; set; } - public Parent Parent { get; set; } + public string ParentId { get; set; } = null!; + public Parent Parent { get; set; } = null!; } public class AnotherChild { public int Id { get; set; } - public string ParentId { get; set; } - public Parent Parent { get; set; } + public string ParentId { get; set; } = null!; + public Parent Parent { get; set; } = null!; } } @@ -274,7 +272,7 @@ protected class Context25225(DbContextOptions options) : DbContext(options) public static readonly Guid Parent2Id = new("e79c82f4-3ae7-4c65-85db-04e08cba6fa7"); public static readonly Guid Collection1Id = new("7ce625fb-863d-41b3-b42e-e4e4367f7548"); public static readonly Guid Collection2Id = new("d347bbd5-003a-441f-a148-df8ab8ac4a29"); - public DbSet Parents { get; set; } + public DbSet Parents { get; set; } = null!; public async Task SeedAsync() { @@ -287,20 +285,20 @@ public async Task SeedAsync() public class Parent { public Guid Id { get; set; } - public ICollection Collection { get; set; } + public ICollection Collection { get; set; } = null!; } public class Collection { public Guid Id { get; set; } public Guid ParentId { get; set; } - public Parent Parent { get; set; } + public Parent Parent { get; set; } = null!; } public class ParentViewModel { public Guid Id { get; set; } - public ICollection Collection { get; set; } + public ICollection Collection { get; set; } = null!; } public class CollectionViewModel @@ -335,7 +333,7 @@ public virtual async Task NoTracking_split_query_creates_only_required_instances // Protected so that it can be used by inheriting tests, and so that things like unused setters are not removed. protected class Context25400(DbContextOptions options) : DbContext(options) { - public DbSet Tests { get; set; } + public DbSet Tests { get; set; } = null!; protected override void OnModelCreating(ModelBuilder modelBuilder) => modelBuilder.Entity().HasKey(e => e.Id); @@ -458,11 +456,11 @@ protected virtual TestStore CreateTestStore33826() protected class Context33826(DbContextOptions options) : DbContext(options) { - public static Func ConcurrentContextFactory { get; set; } + public static Func? ConcurrentContextFactory { get; set; } public static bool InsertConcurrentEntity { get; set; } public static bool DeleteOtherParentsChildren { get; set; } - public DbSet Blogs { get; set; } + public DbSet Blogs { get; set; } = null!; protected override void OnModelCreating(ModelBuilder modelBuilder) { @@ -512,7 +510,7 @@ private Blog33826(int id, int secondId) { Context33826.InsertConcurrentEntity = false; - using var context = Context33826.ConcurrentContextFactory(); + using var context = Context33826.ConcurrentContextFactory!(); context.Blogs.Add(new Blog33826(15, 3, [new Post33826(5, 3, "Concurrent")])); context.SaveChanges(); } @@ -521,7 +519,7 @@ private Blog33826(int id, int secondId) { Context33826.DeleteOtherParentsChildren = false; - using var context = Context33826.ConcurrentContextFactory(); + using var context = Context33826.ConcurrentContextFactory!(); context.Set().Where(p => p.BlogId == 10 && p.BlogSecondId == 2).ExecuteDelete(); } } @@ -593,20 +591,20 @@ public virtual async Task NoTrackingWithIdentityResolution_split_query_complex(b protected class Context34728(DbContextOptions options) : DbContext(options) { - public DbSet Tests { get; set; } + public DbSet Tests { get; set; } = null!; public sealed class Blog { public long Id { get; set; } - public string Name { get; set; } + public string Name { get; set; } = null!; public ISet Posts { get; set; } = new HashSet(); } public sealed class BlogPost { public long Id { get; set; } - public WebAccount Author { get; set; } - public List Tags { get; set; } + public WebAccount Author { get; set; } = null!; + public List Tags { get; set; } = null!; } public sealed class WebAccount @@ -617,7 +615,7 @@ public sealed class WebAccount public sealed class Tag { public int Id { get; set; } - public string Name { get; set; } + public string Name { get; set; } = null!; } } diff --git a/test/EFCore.Relational.Specification.Tests/Query/ComplexNavigationsCollectionsQueryRelationalTestBase.cs b/test/EFCore.Relational.Specification.Tests/Query/ComplexNavigationsCollectionsQueryRelationalTestBase.cs index ecc784471b2..4ff8412a48a 100644 --- a/test/EFCore.Relational.Specification.Tests/Query/ComplexNavigationsCollectionsQueryRelationalTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/Query/ComplexNavigationsCollectionsQueryRelationalTestBase.cs @@ -3,8 +3,6 @@ namespace Microsoft.EntityFrameworkCore.Query; -#nullable disable - public abstract class ComplexNavigationsCollectionsQueryRelationalTestBase(TFixture fixture) : ComplexNavigationsCollectionsQueryTestBase(fixture) diff --git a/test/EFCore.Relational.Specification.Tests/Query/ComplexNavigationsCollectionsSharedTypeQueryRelationalTestBase.cs b/test/EFCore.Relational.Specification.Tests/Query/ComplexNavigationsCollectionsSharedTypeQueryRelationalTestBase.cs index 8cfc501b6a9..fdf59b60bdb 100644 --- a/test/EFCore.Relational.Specification.Tests/Query/ComplexNavigationsCollectionsSharedTypeQueryRelationalTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/Query/ComplexNavigationsCollectionsSharedTypeQueryRelationalTestBase.cs @@ -3,8 +3,6 @@ namespace Microsoft.EntityFrameworkCore.Query; -#nullable disable - public abstract class ComplexNavigationsCollectionsSharedTypeQueryRelationalTestBase(TFixture fixture) : ComplexNavigationsCollectionsSharedTypeQueryTestBase< @@ -14,6 +12,6 @@ public abstract class public override async Task SelectMany_with_navigation_and_Distinct_projecting_columns_including_join_key(bool async) => Assert.Equal( RelationalStrings.InsufficientInformationToIdentifyElementOfCollectionJoin, - (await Assert.ThrowsAsync(() - => base.SelectMany_with_navigation_and_Distinct_projecting_columns_including_join_key(async))).Message); + (await Assert.ThrowsAsync( + () => base.SelectMany_with_navigation_and_Distinct_projecting_columns_including_join_key(async))).Message); } diff --git a/test/EFCore.Relational.Specification.Tests/Query/ComplexNavigationsCollectionsSplitQueryRelationalTestBase.cs b/test/EFCore.Relational.Specification.Tests/Query/ComplexNavigationsCollectionsSplitQueryRelationalTestBase.cs index 5db6709eaf8..0576dcbb162 100644 --- a/test/EFCore.Relational.Specification.Tests/Query/ComplexNavigationsCollectionsSplitQueryRelationalTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/Query/ComplexNavigationsCollectionsSplitQueryRelationalTestBase.cs @@ -3,8 +3,6 @@ namespace Microsoft.EntityFrameworkCore.Query; -#nullable disable - public abstract class ComplexNavigationsCollectionsSplitQueryRelationalTestBase(TFixture fixture) : ComplexNavigationsCollectionsQueryTestBase(fixture) @@ -20,7 +18,7 @@ protected override Expression RewriteServerQueryExpression(Expression serverQuer private class SplitQueryRewritingExpressionVisitor : ExpressionVisitor { private readonly MethodInfo _asSplitQueryMethod - = typeof(RelationalQueryableExtensions).GetMethod(nameof(RelationalQueryableExtensions.AsSplitQuery)); + = typeof(RelationalQueryableExtensions).GetMethod(nameof(RelationalQueryableExtensions.AsSplitQuery))!; protected override Expression VisitExtension(Expression extensionExpression) { diff --git a/test/EFCore.Relational.Specification.Tests/Query/ComplexNavigationsCollectionsSplitSharedTypeQueryRelationalTestBase.cs b/test/EFCore.Relational.Specification.Tests/Query/ComplexNavigationsCollectionsSplitSharedTypeQueryRelationalTestBase.cs index d3eff3a2abd..8c7f45d3f2c 100644 --- a/test/EFCore.Relational.Specification.Tests/Query/ComplexNavigationsCollectionsSplitSharedTypeQueryRelationalTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/Query/ComplexNavigationsCollectionsSplitSharedTypeQueryRelationalTestBase.cs @@ -3,8 +3,6 @@ namespace Microsoft.EntityFrameworkCore.Query; -#nullable disable - public abstract class ComplexNavigationsCollectionsSplitSharedTypeQueryRelationalTestBase(TFixture fixture) : ComplexNavigationsCollectionsSharedTypeQueryTestBase @@ -27,7 +25,7 @@ protected override Expression RewriteServerQueryExpression(Expression serverQuer private class SplitQueryRewritingExpressionVisitor : ExpressionVisitor { private readonly MethodInfo _asSplitQueryMethod - = typeof(RelationalQueryableExtensions).GetMethod(nameof(RelationalQueryableExtensions.AsSplitQuery)); + = typeof(RelationalQueryableExtensions).GetMethod(nameof(RelationalQueryableExtensions.AsSplitQuery))!; protected override Expression VisitExtension(Expression extensionExpression) { diff --git a/test/EFCore.Relational.Specification.Tests/Query/ComplexNavigationsQueryRelationalFixtureBase.cs b/test/EFCore.Relational.Specification.Tests/Query/ComplexNavigationsQueryRelationalFixtureBase.cs index 5e3cf35fdc6..9da3ea00f6d 100644 --- a/test/EFCore.Relational.Specification.Tests/Query/ComplexNavigationsQueryRelationalFixtureBase.cs +++ b/test/EFCore.Relational.Specification.Tests/Query/ComplexNavigationsQueryRelationalFixtureBase.cs @@ -3,8 +3,6 @@ namespace Microsoft.EntityFrameworkCore.Query; -#nullable disable - public abstract class ComplexNavigationsQueryRelationalFixtureBase : ComplexNavigationsQueryFixtureBase, ITestSqlLoggerFactory { public TestSqlLoggerFactory TestSqlLoggerFactory diff --git a/test/EFCore.Relational.Specification.Tests/Query/ComplexNavigationsQueryRelationalTestBase.cs b/test/EFCore.Relational.Specification.Tests/Query/ComplexNavigationsQueryRelationalTestBase.cs index d8097ced8d8..aee92a5992a 100644 --- a/test/EFCore.Relational.Specification.Tests/Query/ComplexNavigationsQueryRelationalTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/Query/ComplexNavigationsQueryRelationalTestBase.cs @@ -3,8 +3,6 @@ namespace Microsoft.EntityFrameworkCore.Query; -#nullable disable - public abstract class ComplexNavigationsQueryRelationalTestBase(TFixture fixture) : ComplexNavigationsQueryTestBase(fixture) where TFixture : ComplexNavigationsQueryFixtureBase, new() diff --git a/test/EFCore.Relational.Specification.Tests/Query/ComplexNavigationsSharedTypeQueryRelationalFixtureBase.cs b/test/EFCore.Relational.Specification.Tests/Query/ComplexNavigationsSharedTypeQueryRelationalFixtureBase.cs index 34b8d1d95c1..267d434a5ee 100644 --- a/test/EFCore.Relational.Specification.Tests/Query/ComplexNavigationsSharedTypeQueryRelationalFixtureBase.cs +++ b/test/EFCore.Relational.Specification.Tests/Query/ComplexNavigationsSharedTypeQueryRelationalFixtureBase.cs @@ -5,8 +5,6 @@ namespace Microsoft.EntityFrameworkCore.Query; -#nullable disable - public abstract class ComplexNavigationsSharedTypeQueryRelationalFixtureBase : ComplexNavigationsSharedTypeQueryFixtureBase, ITestSqlLoggerFactory { diff --git a/test/EFCore.Relational.Specification.Tests/Query/ComplexNavigationsSharedTypeQueryRelationalTestBase.cs b/test/EFCore.Relational.Specification.Tests/Query/ComplexNavigationsSharedTypeQueryRelationalTestBase.cs index d0b029174eb..56a1f8b2368 100644 --- a/test/EFCore.Relational.Specification.Tests/Query/ComplexNavigationsSharedTypeQueryRelationalTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/Query/ComplexNavigationsSharedTypeQueryRelationalTestBase.cs @@ -3,8 +3,6 @@ namespace Microsoft.EntityFrameworkCore.Query; -#nullable disable - public abstract class ComplexNavigationsSharedTypeQueryRelationalTestBase(TFixture fixture) : ComplexNavigationsSharedTypeQueryTestBase(fixture) diff --git a/test/EFCore.Relational.Specification.Tests/Query/ComplexTypeQueryRelationalFixtureBase.cs b/test/EFCore.Relational.Specification.Tests/Query/ComplexTypeQueryRelationalFixtureBase.cs index 42a45784ad4..6cc3e67a578 100644 --- a/test/EFCore.Relational.Specification.Tests/Query/ComplexTypeQueryRelationalFixtureBase.cs +++ b/test/EFCore.Relational.Specification.Tests/Query/ComplexTypeQueryRelationalFixtureBase.cs @@ -3,8 +3,6 @@ namespace Microsoft.EntityFrameworkCore.Query; -#nullable disable - public abstract class ComplexTypeQueryRelationalFixtureBase : ComplexTypeQueryFixtureBase, ITestSqlLoggerFactory { public TestSqlLoggerFactory TestSqlLoggerFactory diff --git a/test/EFCore.Relational.Specification.Tests/Query/ComplexTypeQueryRelationalTestBase.cs b/test/EFCore.Relational.Specification.Tests/Query/ComplexTypeQueryRelationalTestBase.cs index 15483d2b7b4..58f9817f327 100644 --- a/test/EFCore.Relational.Specification.Tests/Query/ComplexTypeQueryRelationalTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/Query/ComplexTypeQueryRelationalTestBase.cs @@ -3,8 +3,6 @@ namespace Microsoft.EntityFrameworkCore.Query; -#nullable disable - public abstract class ComplexTypeQueryRelationalTestBase(TFixture fixture) : ComplexTypeQueryTestBase(fixture) where TFixture : ComplexTypeQueryRelationalFixtureBase, new() { @@ -73,8 +71,6 @@ public override async Task Union_two_different_struct_complex_type(bool async) #region Non-shared test resources -#nullable enable - #region 37205 [Fact] @@ -303,8 +299,6 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) protected TestSqlLoggerFactory TestSqlLoggerFactory => (TestSqlLoggerFactory)ListLoggerFactory; -#nullable disable - #endregion Non-shared test resources private void AssertSql(params string[] expected) diff --git a/test/EFCore.Relational.Specification.Tests/Query/CompositeKeysQueryRelationalFixtureBase.cs b/test/EFCore.Relational.Specification.Tests/Query/CompositeKeysQueryRelationalFixtureBase.cs index 9fb728c4a4f..98de49904f3 100644 --- a/test/EFCore.Relational.Specification.Tests/Query/CompositeKeysQueryRelationalFixtureBase.cs +++ b/test/EFCore.Relational.Specification.Tests/Query/CompositeKeysQueryRelationalFixtureBase.cs @@ -3,8 +3,6 @@ namespace Microsoft.EntityFrameworkCore.Query; -#nullable disable - public abstract class CompositeKeysQueryRelationalFixtureBase : CompositeKeysQueryFixtureBase, ITestSqlLoggerFactory { public TestSqlLoggerFactory TestSqlLoggerFactory diff --git a/test/EFCore.Relational.Specification.Tests/Query/CompositeKeysQueryRelationalTestBase.cs b/test/EFCore.Relational.Specification.Tests/Query/CompositeKeysQueryRelationalTestBase.cs index 35740f38852..bdcf0101c22 100644 --- a/test/EFCore.Relational.Specification.Tests/Query/CompositeKeysQueryRelationalTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/Query/CompositeKeysQueryRelationalTestBase.cs @@ -3,7 +3,5 @@ namespace Microsoft.EntityFrameworkCore.Query; -#nullable disable - public abstract class CompositeKeysQueryRelationalTestBase(TFixture fixture) : CompositeKeysQueryTestBase(fixture) where TFixture : CompositeKeysQueryFixtureBase, new(); diff --git a/test/EFCore.Relational.Specification.Tests/Query/CompositeKeysSplitQueryRelationalTestBase.cs b/test/EFCore.Relational.Specification.Tests/Query/CompositeKeysSplitQueryRelationalTestBase.cs index 6ae4e946c56..e36fa1695a9 100644 --- a/test/EFCore.Relational.Specification.Tests/Query/CompositeKeysSplitQueryRelationalTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/Query/CompositeKeysSplitQueryRelationalTestBase.cs @@ -3,8 +3,6 @@ namespace Microsoft.EntityFrameworkCore.Query; -#nullable disable - public abstract class CompositeKeysSplitQueryRelationalTestBase(TFixture fixture) : CompositeKeysQueryTestBase(fixture) where TFixture : CompositeKeysQueryFixtureBase, new() { @@ -18,7 +16,7 @@ protected override Expression RewriteServerQueryExpression(Expression serverQuer private class SplitQueryRewritingExpressionVisitor : ExpressionVisitor { private readonly MethodInfo _asSplitQueryMethod - = typeof(RelationalQueryableExtensions).GetMethod(nameof(RelationalQueryableExtensions.AsSplitQuery)); + = typeof(RelationalQueryableExtensions).GetMethod(nameof(RelationalQueryableExtensions.AsSplitQuery))!; protected override Expression VisitExtension(Expression extensionExpression) { diff --git a/test/EFCore.Relational.Specification.Tests/Query/EntitySplittingQueryTestBase.cs b/test/EFCore.Relational.Specification.Tests/Query/EntitySplittingQueryTestBase.cs index 4523abd0381..b9d49ab3d8e 100644 --- a/test/EFCore.Relational.Specification.Tests/Query/EntitySplittingQueryTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/Query/EntitySplittingQueryTestBase.cs @@ -9,8 +9,6 @@ namespace Microsoft.EntityFrameworkCore.Query; -#nullable disable - public abstract class EntitySplittingQueryTestBase : NonSharedModelTestBase, IClassFixture { protected EntitySplittingQueryTestBase(NonSharedFixture fixture) @@ -188,7 +186,7 @@ await InitializeContextFactoryAsync(mb => mb.Entity(b => await AssertQuery( async, ss => ss.Set().Include(e => e.EntityOne), - elementAsserter: (e, a) => AssertInclude(e, a, new ExpectedInclude(i => i.EntityOne)), + elementAsserter: (e, a) => AssertInclude(e, a, new ExpectedInclude(i => i.EntityOne!)), entryCount: 8); } @@ -245,11 +243,11 @@ await InitializeContextFactoryAsync(mb => mb.Entity(b => await AssertQuery( async, - ss => ss.Set().Include(e => e.EntityOne.EntityThree), + ss => ss.Set().Include(e => e.EntityOne!.EntityThree), elementAsserter: (e, a) => AssertInclude( e, a, - new ExpectedInclude(i => i.EntityOne), - new ExpectedInclude(i => i.EntityThree)), + new ExpectedInclude(i => i.EntityOne!), + new ExpectedInclude(i => i.EntityThree!)), entryCount: 10); } @@ -310,7 +308,7 @@ await InitializeContextFactoryAsync(mb => mb.Entity(b => await AssertQuery( async, ss => ss.Set().Include(e => e.EntityThree), - elementAsserter: (e, a) => AssertInclude(e, a, new ExpectedInclude(i => i.EntityThree)), + elementAsserter: (e, a) => AssertInclude(e, a, new ExpectedInclude(i => i.EntityThree!)), entryCount: 8); } @@ -410,7 +408,7 @@ await InitializeContextFactoryAsync(mb => mb.Entity(b => b.OwnsOne( await AssertQuery( async, ss => ss.Set(), - elementAsserter: (e, a) => AssertInclude(e, a, new ExpectedInclude(i => i.OwnedReference)), + elementAsserter: (e, a) => AssertInclude(e, a, new ExpectedInclude(i => i.OwnedReference!)), entryCount: 10); } @@ -448,7 +446,7 @@ await AssertQuery( ss => ss.Set().Select(e => new { e.Id, - e.OwnedReference.OwnedIntValue4, + e.OwnedReference!.OwnedIntValue4, e.OwnedReference.OwnedStringValue4 }), elementSorter: e => e.Id, @@ -495,7 +493,7 @@ await InitializeContextFactoryAsync(mb => mb.Entity(b => await AssertQuery( async, ss => ss.Set(), - elementAsserter: (e, a) => AssertInclude(e, a, new ExpectedInclude(i => i.OwnedReference)), + elementAsserter: (e, a) => AssertInclude(e, a, new ExpectedInclude(i => i.OwnedReference!)), entryCount: 10); } @@ -535,7 +533,7 @@ await AssertQuery( ss => ss.Set().Select(e => new { e.Id, - e.OwnedReference.OwnedIntValue4, + e.OwnedReference!.OwnedIntValue4, e.OwnedReference.OwnedStringValue4 }), elementSorter: e => e.Id, @@ -641,8 +639,8 @@ await AssertQuery( ss => ss.Set(), elementAsserter: (e, a) => AssertInclude( e, a, - new ExpectedInclude(i => i.OwnedReference), - new ExpectedInclude(i => i.OwnedNestedReference)), + new ExpectedInclude(i => i.OwnedReference!), + new ExpectedInclude(i => i.OwnedNestedReference!)), entryCount: 15); } @@ -676,7 +674,7 @@ await InitializeContextFactoryAsync(mb => await AssertQuery( async, ss => ss.Set(), - elementAsserter: (e, a) => AssertInclude(e, a, new ExpectedInclude(i => i.OwnedReference)), + elementAsserter: (e, a) => AssertInclude(e, a, new ExpectedInclude(i => i.OwnedReference!)), entryCount: 10); } @@ -762,7 +760,7 @@ await InitializeContextFactoryAsync(mb => mb.Entity(b => await AssertQuery( async, ss => ss.Set(), - elementAsserter: (e, a) => AssertInclude(e, a, new ExpectedInclude(i => i.OwnedReference)), + elementAsserter: (e, a) => AssertInclude(e, a, new ExpectedInclude(i => i.OwnedReference!)), entryCount: 10); } @@ -868,7 +866,7 @@ await InitializeContextFactoryAsync(mb => mb.Entity(b => await AssertQuery( async, ss => ss.Set(), - elementAsserter: (e, a) => AssertInclude(e, a, new ExpectedInclude(i => i.OwnedReference)), + elementAsserter: (e, a) => AssertInclude(e, a, new ExpectedInclude(i => i.OwnedReference!)), entryCount: 10); } @@ -922,7 +920,7 @@ await InitializeContextFactoryAsync(mb => mb.Entity(b => await AssertQuery( async, ss => ss.Set(), - elementAsserter: (e, a) => AssertInclude(e, a, new ExpectedInclude(i => i.OwnedReference)), + elementAsserter: (e, a) => AssertInclude(e, a, new ExpectedInclude(i => i.OwnedReference!)), entryCount: 10); } @@ -976,7 +974,7 @@ await InitializeContextFactoryAsync(mb => mb.Entity(b => await AssertQuery( async, ss => ss.Set(), - elementAsserter: (e, a) => AssertInclude(e, a, new ExpectedInclude(i => i.OwnedReference)), + elementAsserter: (e, a) => AssertInclude(e, a, new ExpectedInclude(i => i.OwnedReference!)), entryCount: 10); } @@ -1008,7 +1006,7 @@ await InitializeContextFactoryAsync(mb => mb.Entity() await AssertQuery( async, ss => ss.Set(), - elementAsserter: (e, a) => AssertInclude(e, a, new ExpectedInclude(i => i.OwnedReference)), + elementAsserter: (e, a) => AssertInclude(e, a, new ExpectedInclude(i => i.OwnedReference!)), entryCount: 8); } @@ -1045,7 +1043,7 @@ await InitializeContextFactoryAsync(mb => await AssertQuery( async, ss => ss.Set(), - elementAsserter: (e, a) => AssertInclude(e, a, new ExpectedInclude(i => i.OwnedReference)), + elementAsserter: (e, a) => AssertInclude(e, a, new ExpectedInclude(i => i.OwnedReference!)), entryCount: 8); } @@ -1077,7 +1075,7 @@ await InitializeContextFactoryAsync(mb => mb.Entity() await AssertQuery( async, ss => ss.Set(), - elementAsserter: (e, a) => AssertInclude(e, a, new ExpectedInclude(i => i.OwnedReference)), + elementAsserter: (e, a) => AssertInclude(e, a, new ExpectedInclude(i => i.OwnedReference!)), entryCount: 6); } @@ -1114,7 +1112,7 @@ await InitializeContextFactoryAsync(mb => await AssertQuery( async, ss => ss.Set(), - elementAsserter: (e, a) => AssertInclude(e, a, new ExpectedInclude(i => i.OwnedReference)), + elementAsserter: (e, a) => AssertInclude(e, a, new ExpectedInclude(i => i.OwnedReference!)), entryCount: 6); } @@ -1146,7 +1144,7 @@ await InitializeContextFactoryAsync(mb => mb.Entity() await AssertQuery( async, ss => ss.Set(), - elementAsserter: (e, a) => AssertInclude(e, a, new ExpectedInclude(i => i.OwnedReference)), + elementAsserter: (e, a) => AssertInclude(e, a, new ExpectedInclude(i => i.OwnedReference!)), entryCount: 5); } @@ -1183,7 +1181,7 @@ await InitializeContextFactoryAsync(mb => await AssertQuery( async, ss => ss.Set(), - elementAsserter: (e, a) => AssertInclude(e, a, new ExpectedInclude(i => i.OwnedReference)), + elementAsserter: (e, a) => AssertInclude(e, a, new ExpectedInclude(i => i.OwnedReference!)), entryCount: 5); } @@ -1220,7 +1218,7 @@ await InitializeContextFactoryAsync(mb => await AssertQuery( async, ss => ss.Set(), - elementAsserter: (e, a) => AssertInclude(e, a, new ExpectedInclude(i => i.OwnedReference)), + elementAsserter: (e, a) => AssertInclude(e, a, new ExpectedInclude(i => i.OwnedReference!)), entryCount: 5); } @@ -1252,7 +1250,7 @@ await InitializeContextFactoryAsync(mb => mb.Entity() await AssertQuery( async, ss => ss.Set(), - elementAsserter: (e, a) => AssertInclude(e, a, new ExpectedInclude(i => i.OwnedReference)), + elementAsserter: (e, a) => AssertInclude(e, a, new ExpectedInclude(i => i.OwnedReference!)), entryCount: 2); } @@ -1289,7 +1287,7 @@ await InitializeContextFactoryAsync(mb => await AssertQuery( async, ss => ss.Set(), - elementAsserter: (e, a) => AssertInclude(e, a, new ExpectedInclude(i => i.OwnedReference)), + elementAsserter: (e, a) => AssertInclude(e, a, new ExpectedInclude(i => i.OwnedReference!)), entryCount: 2); } @@ -1498,7 +1496,7 @@ await InitializeContextFactoryAsync(mb => mb.Entity() await AssertQuery( async, ss => ss.Set(), - elementAsserter: (e, a) => AssertInclude(e, a, new ExpectedInclude(i => i.OwnedReference)), + elementAsserter: (e, a) => AssertInclude(e, a, new ExpectedInclude(i => i.OwnedReference!)), entryCount: 8); } @@ -1537,7 +1535,7 @@ await InitializeContextFactoryAsync(mb => await AssertQuery( async, ss => ss.Set(), - elementAsserter: (e, a) => AssertInclude(e, a, new ExpectedInclude(i => i.OwnedReference)), + elementAsserter: (e, a) => AssertInclude(e, a, new ExpectedInclude(i => i.OwnedReference!)), entryCount: 8); } @@ -1576,7 +1574,7 @@ await InitializeContextFactoryAsync(mb => await AssertQuery( async, ss => ss.Set(), - elementAsserter: (e, a) => AssertInclude(e, a, new ExpectedInclude(i => i.OwnedReference)), + elementAsserter: (e, a) => AssertInclude(e, a, new ExpectedInclude(i => i.OwnedReference!)), entryCount: 8); } @@ -1610,7 +1608,7 @@ await InitializeContextFactoryAsync(mb => mb.Entity() await AssertQuery( async, ss => ss.Set(), - elementAsserter: (e, a) => AssertInclude(e, a, new ExpectedInclude(i => i.OwnedReference)), + elementAsserter: (e, a) => AssertInclude(e, a, new ExpectedInclude(i => i.OwnedReference!)), entryCount: 6); } @@ -1649,7 +1647,7 @@ await InitializeContextFactoryAsync(mb => await AssertQuery( async, ss => ss.Set(), - elementAsserter: (e, a) => AssertInclude(e, a, new ExpectedInclude(i => i.OwnedReference)), + elementAsserter: (e, a) => AssertInclude(e, a, new ExpectedInclude(i => i.OwnedReference!)), entryCount: 6); } @@ -1688,7 +1686,7 @@ await InitializeContextFactoryAsync(mb => await AssertQuery( async, ss => ss.Set(), - elementAsserter: (e, a) => AssertInclude(e, a, new ExpectedInclude(i => i.OwnedReference)), + elementAsserter: (e, a) => AssertInclude(e, a, new ExpectedInclude(i => i.OwnedReference!)), entryCount: 6); } @@ -1722,7 +1720,7 @@ await InitializeContextFactoryAsync(mb => mb.Entity() await AssertQuery( async, ss => ss.Set(), - elementAsserter: (e, a) => AssertInclude(e, a, new ExpectedInclude(i => i.OwnedReference)), + elementAsserter: (e, a) => AssertInclude(e, a, new ExpectedInclude(i => i.OwnedReference!)), entryCount: 5); } @@ -1761,7 +1759,7 @@ await InitializeContextFactoryAsync(mb => await AssertQuery( async, ss => ss.Set(), - elementAsserter: (e, a) => AssertInclude(e, a, new ExpectedInclude(i => i.OwnedReference)), + elementAsserter: (e, a) => AssertInclude(e, a, new ExpectedInclude(i => i.OwnedReference!)), entryCount: 5); } @@ -1800,7 +1798,7 @@ await InitializeContextFactoryAsync(mb => await AssertQuery( async, ss => ss.Set(), - elementAsserter: (e, a) => AssertInclude(e, a, new ExpectedInclude(i => i.OwnedReference)), + elementAsserter: (e, a) => AssertInclude(e, a, new ExpectedInclude(i => i.OwnedReference!)), entryCount: 5); } @@ -2201,8 +2199,8 @@ protected string NormalizeDelimitersInRawString(string sql) protected async Task AssertQuery( bool async, Func> queryCreator, - Func elementSorter = null, - Action elementAsserter = null, + Func? elementSorter = null, + Action? elementAsserter = null, bool assertOrder = false, int entryCount = 0) where TResult : class @@ -2223,13 +2221,13 @@ protected async Task AssertQuery( && elementSorter == null) { EntitySorters.TryGetValue(typeof(TResult), out var sorter); - elementSorter = (Func)sorter; + elementSorter = (Func?)sorter; } if (elementAsserter == null) { EntityAsserters.TryGetValue(typeof(TResult), out var asserter); - elementAsserter = (Action)asserter; + elementAsserter = (Action?)asserter; } TestHelpers.AssertResults( @@ -2242,13 +2240,13 @@ protected async Task AssertQuery( Assert.Equal(entryCount, context.ChangeTracker.Entries().Count()); } - protected void AssertEqual(T expected, T actual, Action asserter = null) + protected void AssertEqual(T expected, T actual, Action? asserter = null) { if (asserter == null && expected != null) { EntityAsserters.TryGetValue(typeof(T), out var entityAsserter); - asserter ??= (Action)entityAsserter; + asserter ??= (Action?)entityAsserter; } asserter ??= Assert.Equal; @@ -2256,11 +2254,11 @@ protected void AssertEqual(T expected, T actual, Action asserter = null } protected void AssertCollection( - IEnumerable expected, - IEnumerable actual, + IEnumerable? expected, + IEnumerable? actual, bool ordered = false, - Func elementSorter = null, - Action elementAsserter = null) + Func? elementSorter = null, + Action? elementAsserter = null) { if (expected == null @@ -2269,7 +2267,7 @@ protected void AssertCollection( return; } - if (expected == null != (actual == null)) + if (expected == null || actual == null) { throw new InvalidOperationException( $"Nullability doesn't match. Expected: {(expected == null ? "NULL" : "NOT NULL")}. Actual: {(actual == null ? "NULL." : "NOT NULL.")}."); @@ -2278,8 +2276,8 @@ protected void AssertCollection( EntitySorters.TryGetValue(typeof(TElement), out var sorter); EntityAsserters.TryGetValue(typeof(TElement), out var asserter); - elementSorter ??= (Func)sorter; - elementAsserter ??= (Action)asserter ?? Assert.Equal; + elementSorter ??= (Func?)sorter; + elementAsserter ??= (Action?)asserter ?? Assert.Equal; if (!ordered) { @@ -2320,13 +2318,13 @@ protected void AssertCollection( } private static readonly MethodInfo _assertIncludeEntity = - typeof(EntitySplittingQueryTestBase).GetTypeInfo().GetDeclaredMethod(nameof(AssertIncludeEntity)); + typeof(EntitySplittingQueryTestBase).GetTypeInfo().GetDeclaredMethod(nameof(AssertIncludeEntity))!; private static readonly MethodInfo _assertIncludeCollectionMethodInfo = - typeof(EntitySplittingQueryTestBase).GetTypeInfo().GetDeclaredMethod(nameof(AssertIncludeCollection)); + typeof(EntitySplittingQueryTestBase).GetTypeInfo().GetDeclaredMethod(nameof(AssertIncludeCollection))!; private static readonly MethodInfo _filteredIncludeMethodInfo = - typeof(EntitySplittingQueryTestBase).GetTypeInfo().GetDeclaredMethod(nameof(FilteredInclude)); + typeof(EntitySplittingQueryTestBase).GetTypeInfo().GetDeclaredMethod(nameof(FilteredInclude))!; private readonly List _includePath = []; @@ -2343,7 +2341,7 @@ private void AssertIncludeInternal(TEntity expected, TEntity actual, IE AssertIncludeObject(expected, actual, expectedIncludes, assertOrder: false); } - private void AssertIncludeObject(object expected, object actual, IEnumerable expectedIncludes, bool assertOrder) + private void AssertIncludeObject(object? expected, object? actual, IEnumerable expectedIncludes, bool assertOrder) { if (expected == null && actual == null) @@ -2353,7 +2351,7 @@ private void AssertIncludeObject(object expected, object actual, IEnumerable i.IsConstructedGenericType && i.GetGenericTypeDefinition() == typeof(IEnumerable<>))) @@ -2369,7 +2367,7 @@ private void AssertIncludeObject(object expected, object actual, IEnumerable(TElement expected, TElement actual, IEnumerable expectedIncludes) { - Assert.Equal(expected.GetType(), actual.GetType()); + Assert.Equal(expected!.GetType(), actual!.GetType()); if (EntityAsserters.TryGetValue(typeof(TElement), out var asserter)) { @@ -2402,7 +2400,7 @@ private void AssertIncludeCollection( for (var i = 0; i < expectedList.Count; i++) { - var elementType = expectedList[i].GetType(); + var elementType = expectedList[i]!.GetType(); _assertIncludeEntity.MakeGenericMethod(elementType) .Invoke(this, [expectedList[i], actualList[i], expectedIncludes]); } @@ -2428,8 +2426,8 @@ private void ProcessIncludes(TEntity expected, TEntity actual, IEnumera CultureInfo.CurrentCulture); assertOrder = (bool)expectedInclude.GetType() - .GetProperty(nameof(ExpectedFilteredInclude.AssertOrder)) - .GetValue(expectedInclude); + .GetProperty(nameof(ExpectedFilteredInclude.AssertOrder))! + .GetValue(expectedInclude)!; } var actualIncludedNavigation = GetIncluded(actual, expectedInclude.IncludeMember); @@ -2447,7 +2445,7 @@ private IEnumerable FilteredInclude( ExpectedFilteredInclude expectedFilteredInclude) => expectedFilteredInclude.IncludeFilter(expected); - private object GetIncluded(TEntity entity, MemberInfo includeMember) + private object? GetIncluded(TEntity entity, MemberInfo includeMember) => includeMember switch { FieldInfo fieldInfo => fieldInfo.GetValue(entity), @@ -2459,16 +2457,16 @@ protected void AssertGrouping( IGrouping expected, IGrouping actual, bool ordered = false, - Func elementSorter = null, - Action keyAsserter = null, - Action elementAsserter = null) + Func? elementSorter = null, + Action? keyAsserter = null, + Action? elementAsserter = null) { keyAsserter ??= Assert.Equal; keyAsserter(expected.Key, actual.Key); AssertCollection(expected, actual, ordered, elementSorter, elementAsserter); } - private void OrderingSettingsVerifier(bool assertOrder, Type type, object elementSorter) + private void OrderingSettingsVerifier(bool assertOrder, Type type, object? elementSorter) { if (!assertOrder && type.IsGenericType @@ -2495,7 +2493,7 @@ protected void AssertSql(params string[] expected) // These are static so that they are shared across tests private static IReadOnlyDictionary EntityAsserters { get; } - = new Dictionary> + = new Dictionary> { { typeof(EntityOne), (e, a) => @@ -2503,7 +2501,7 @@ protected void AssertSql(params string[] expected) Assert.Equal(e == null, a == null); if (a != null) { - var ee = (EntityOne)e; + var ee = (EntityOne)e!; var aa = (EntityOne)a; Assert.Equal(ee.Id, aa.Id); @@ -2524,7 +2522,7 @@ protected void AssertSql(params string[] expected) Assert.Equal(e == null, a == null); if (a != null) { - var ee = (EntityTwo)e; + var ee = (EntityTwo)e!; var aa = (EntityTwo)a; Assert.Equal(ee.Id, aa.Id); @@ -2538,7 +2536,7 @@ protected void AssertSql(params string[] expected) Assert.Equal(e == null, a == null); if (a != null) { - var ee = (EntityThree)e; + var ee = (EntityThree)e!; var aa = (EntityThree)a; Assert.Equal(ee.Id, aa.Id); @@ -2552,7 +2550,7 @@ protected void AssertSql(params string[] expected) Assert.Equal(e == null, a == null); if (a != null) { - var ee = (BaseEntity)e; + var ee = (BaseEntity)e!; var aa = (BaseEntity)a; Assert.Equal(ee.Id, aa.Id); @@ -2583,7 +2581,7 @@ protected void AssertSql(params string[] expected) Assert.Equal(e == null, a == null); if (a != null) { - var ee = (MiddleEntity)e; + var ee = (MiddleEntity)e!; var aa = (MiddleEntity)a; Assert.Equal(ee.Id, aa.Id); @@ -2604,7 +2602,7 @@ protected void AssertSql(params string[] expected) Assert.Equal(e == null, a == null); if (a != null) { - var ee = (SiblingEntity)e; + var ee = (SiblingEntity)e!; var aa = (SiblingEntity)a; Assert.Equal(ee.Id, aa.Id); @@ -2619,7 +2617,7 @@ protected void AssertSql(params string[] expected) Assert.Equal(e == null, a == null); if (a != null) { - var ee = (LeafEntity)e; + var ee = (LeafEntity)e!; var aa = (LeafEntity)a; Assert.Equal(ee.Id, aa.Id); @@ -2635,7 +2633,7 @@ protected void AssertSql(params string[] expected) Assert.Equal(e == null, a == null); if (a != null) { - var ee = (OwnedReference)e; + var ee = (OwnedReference)e!; var aa = (OwnedReference)a; Assert.Equal(ee.Id, aa.Id); @@ -2656,7 +2654,7 @@ protected void AssertSql(params string[] expected) Assert.Equal(e == null, a == null); if (a != null) { - var ee = (OwnedNestedReference)e; + var ee = (OwnedNestedReference)e!; var aa = (OwnedNestedReference)a; Assert.Equal(ee.Id, aa.Id); @@ -2677,7 +2675,7 @@ protected void AssertSql(params string[] expected) Assert.Equal(e == null, a == null); if (a != null) { - var ee = (OwnedCollection)e; + var ee = (OwnedCollection)e!; var aa = (OwnedCollection)a; Assert.Equal(ee.Id, aa.Id); @@ -2691,7 +2689,7 @@ protected void AssertSql(params string[] expected) }.ToDictionary(e => e.Key, e => (object)e.Value); private static IReadOnlyDictionary EntitySorters { get; } - = new Dictionary> + = new Dictionary> { { typeof(EntityOne), e => ((EntityOne)e)?.Id }, { typeof(EntityTwo), e => ((EntityTwo)e)?.Id }, @@ -2753,7 +2751,7 @@ protected override string NonSharedStoreName protected TestSqlLoggerFactory TestSqlLoggerFactory => (TestSqlLoggerFactory)ListLoggerFactory; - protected ContextFactory ContextFactory { get; private set; } + protected ContextFactory ContextFactory { get; private set; } = null!; protected virtual void OnModelCreating(ModelBuilder modelBuilder) { @@ -2770,7 +2768,7 @@ public override async ValueTask DisposeAsync() { await base.DisposeAsync(); - ContextFactory = null; + ContextFactory = null!; } #endregion diff --git a/test/EFCore.Relational.Specification.Tests/Query/FromSqlQueryTestBase.cs b/test/EFCore.Relational.Specification.Tests/Query/FromSqlQueryTestBase.cs index 59d2776b332..6fc8527c422 100644 --- a/test/EFCore.Relational.Specification.Tests/Query/FromSqlQueryTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/Query/FromSqlQueryTestBase.cs @@ -143,7 +143,7 @@ public virtual Task FromSqlRaw_queryable_simple(bool async) async, ss => ((DbSet)ss.Set()) .FromSqlRaw(NormalizeDelimitersInRawString("SELECT * FROM [Customers] WHERE [ContactName] LIKE '%z%'")), - ss => ss.Set().Where(x => x.ContactName.Contains("z"))); + ss => ss.Set().Where(x => x.ContactName!.Contains("z"))); [Theory, MemberData(nameof(IsAsyncData))] public virtual Task FromSqlRaw_queryable_simple_columns_out_of_order(bool async) @@ -198,8 +198,8 @@ public virtual Task FromSqlRaw_queryable_composed(bool async) => AssertQuery( async, ss => ((DbSet)ss.Set()).FromSqlRaw(NormalizeDelimitersInRawString("SELECT * FROM [Customers]")) - .Where(c => c.ContactName.Contains("z")), - ss => ss.Set().Where(c => c.ContactName.Contains("z"))); + .Where(c => c.ContactName!.Contains("z")), + ss => ss.Set().Where(c => c.ContactName!.Contains("z"))); [Theory, MemberData(nameof(IsAsyncData))] public virtual Task FromSqlRaw_queryable_composed_after_removing_whitespaces(bool async) @@ -208,8 +208,8 @@ public virtual Task FromSqlRaw_queryable_composed_after_removing_whitespaces(boo ss => ((DbSet)ss.Set()).FromSqlRaw( NormalizeDelimitersInRawString( _eol + " " + _eol + _eol + _eol + "SELECT" + _eol + "* FROM [Customers]")) - .Where(c => c.ContactName.Contains("z")), - ss => ss.Set().Where(c => c.ContactName.Contains("z"))); + .Where(c => c.ContactName!.Contains("z")), + ss => ss.Set().Where(c => c.ContactName!.Contains("z"))); [Theory, MemberData(nameof(IsAsyncData))] public virtual async Task FromSqlRaw_queryable_composed_compiled(bool async) @@ -218,7 +218,7 @@ public virtual async Task FromSqlRaw_queryable_composed_compiled(bool async) { var query = EF.CompileAsyncQuery((NorthwindContext context) => context.Set() .FromSqlRaw(NormalizeDelimitersInRawString("SELECT * FROM [Customers]")) - .Where(c => c.ContactName.Contains("z"))); + .Where(c => c.ContactName!.Contains("z"))); using (var context = CreateContext()) { @@ -231,7 +231,7 @@ public virtual async Task FromSqlRaw_queryable_composed_compiled(bool async) { var query = EF.CompileQuery((NorthwindContext context) => context.Set() .FromSqlRaw(NormalizeDelimitersInRawString("SELECT * FROM [Customers]")) - .Where(c => c.ContactName.Contains("z"))); + .Where(c => c.ContactName!.Contains("z"))); using (var context = CreateContext()) { @@ -250,7 +250,7 @@ public virtual async Task FromSqlRaw_queryable_composed_compiled_with_parameter( var query = EF.CompileAsyncQuery((NorthwindContext context) => context.Set() .FromSqlRaw( NormalizeDelimitersInRawString("SELECT * FROM [Customers] WHERE [CustomerID] = {0}"), "CONSH") - .Where(c => c.ContactName.Contains("z"))); + .Where(c => c.ContactName!.Contains("z"))); using (var context = CreateContext()) { @@ -264,7 +264,7 @@ public virtual async Task FromSqlRaw_queryable_composed_compiled_with_parameter( var query = EF.CompileQuery((NorthwindContext context) => context.Set() .FromSqlRaw( NormalizeDelimitersInRawString("SELECT * FROM [Customers] WHERE [CustomerID] = {0}"), "CONSH") - .Where(c => c.ContactName.Contains("z"))); + .Where(c => c.ContactName!.Contains("z"))); using (var context = CreateContext()) { @@ -284,7 +284,7 @@ public virtual async Task FromSqlRaw_queryable_composed_compiled_with_DbParamete .FromSqlRaw( NormalizeDelimitersInRawString("SELECT * FROM [Customers] WHERE [CustomerID] = @customer"), CreateDbParameter("customer", "CONSH")) - .Where(c => c.ContactName.Contains("z"))); + .Where(c => c.ContactName!.Contains("z"))); using (var context = CreateContext()) { @@ -299,7 +299,7 @@ public virtual async Task FromSqlRaw_queryable_composed_compiled_with_DbParamete .FromSqlRaw( NormalizeDelimitersInRawString("SELECT * FROM [Customers] WHERE [CustomerID] = @customer"), CreateDbParameter("customer", "CONSH")) - .Where(c => c.ContactName.Contains("z"))); + .Where(c => c.ContactName!.Contains("z"))); using (var context = CreateContext()) { @@ -319,7 +319,7 @@ public virtual async Task FromSqlRaw_queryable_composed_compiled_with_nameless_D .FromSqlRaw( NormalizeDelimitersInRawString("SELECT * FROM [Customers] WHERE [CustomerID] = {0}"), CreateDbParameter(null!, "CONSH")) - .Where(c => c.ContactName.Contains("z"))); + .Where(c => c.ContactName!.Contains("z"))); using (var context = CreateContext()) { @@ -334,7 +334,7 @@ public virtual async Task FromSqlRaw_queryable_composed_compiled_with_nameless_D .FromSqlRaw( NormalizeDelimitersInRawString("SELECT * FROM [Customers] WHERE [CustomerID] = {0}"), CreateDbParameter(null!, "CONSH")) - .Where(c => c.ContactName.Contains("z"))); + .Where(c => c.ContactName!.Contains("z"))); using (var context = CreateContext()) { @@ -1093,7 +1093,7 @@ public virtual Task Keyless_entity_with_all_nulls(bool async) ss => ((DbSet)ss.Set()) .FromSqlRaw(NormalizeDelimitersInRawString("SELECT NULL AS [CustomerID] FROM [Customers] WHERE [City] = 'Berlin'")) .IgnoreQueryFilters(), - ss => ss.Set().Where(x => x.City == "Berlin").Select(x => new OrderQuery(null))); + ss => ss.Set().Where(x => x.City == "Berlin").Select(x => new OrderQuery(null!))); [Theory, MemberData(nameof(IsAsyncData))] public virtual async Task FromSql_used_twice_without_parameters(bool async) @@ -1300,8 +1300,8 @@ public virtual Task FromSqlRaw_composed_with_common_table_expression(bool async) SELECT * FROM [Customers] ) SELECT * FROM [Customers2]")) - .Where(c => c.ContactName.Contains("z")), - ss => ss.Set().Where(c => c.ContactName.Contains("z"))); + .Where(c => c.ContactName!.Contains("z")), + ss => ss.Set().Where(c => c.ContactName!.Contains("z"))); [Theory, MemberData(nameof(IsAsyncData))] public virtual async Task Multiple_occurrences_of_FromSql_with_db_parameter_adds_two_parameters(bool async) diff --git a/test/EFCore.Relational.Specification.Tests/Query/FromSqlSprocQueryTestBase.cs b/test/EFCore.Relational.Specification.Tests/Query/FromSqlSprocQueryTestBase.cs index a7f97b84bd6..145894f3140 100644 --- a/test/EFCore.Relational.Specification.Tests/Query/FromSqlSprocQueryTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/Query/FromSqlSprocQueryTestBase.cs @@ -6,8 +6,6 @@ // ReSharper disable InconsistentNaming namespace Microsoft.EntityFrameworkCore.Query; -#nullable disable - public abstract class FromSqlSprocQueryTestBase(TFixture fixture) : IClassFixture where TFixture : NorthwindQueryRelationalFixture, new() { @@ -193,7 +191,7 @@ public virtual async Task From_sql_queryable_stored_procedure_composed(bool asyn var query = context .Set() .FromSqlRaw(TenMostExpensiveProductsSproc, GetTenMostExpensiveProductsParameters()) - .Where(mep => mep.TenMostExpensiveProducts.Contains("C")) + .Where(mep => mep.TenMostExpensiveProducts!.Contains("C")) .OrderBy(mep => mep.UnitPrice); Assert.Equal( @@ -214,7 +212,7 @@ public virtual async Task From_sql_queryable_stored_procedure_composed_on_client var actual = (async ? await query.ToListAsync() : query.ToList()) - .Where(mep => mep.TenMostExpensiveProducts.Contains("C")) + .Where(mep => mep.TenMostExpensiveProducts!.Contains("C")) .OrderBy(mep => mep.UnitPrice) .ToArray(); @@ -231,7 +229,7 @@ public virtual async Task From_sql_queryable_stored_procedure_with_parameter_com var query = context .Set() .FromSqlRaw(CustomerOrderHistorySproc, GetCustomerOrderHistorySprocParameters()) - .Where(coh => coh.ProductName.Contains("C")) + .Where(coh => coh.ProductName!.Contains("C")) .OrderBy(coh => coh.Total); Assert.Equal( @@ -252,7 +250,7 @@ public virtual async Task From_sql_queryable_stored_procedure_with_parameter_com var actual = (async ? await query.ToListAsync() : query.ToList()) - .Where(coh => coh.ProductName.Contains("C")) + .Where(coh => coh.ProductName!.Contains("C")) .OrderBy(coh => coh.Total) .ToArray(); diff --git a/test/EFCore.Relational.Specification.Tests/Query/GearsOfWarFromSqlQueryTestBase.cs b/test/EFCore.Relational.Specification.Tests/Query/GearsOfWarFromSqlQueryTestBase.cs index 8afee004130..9cf4a857673 100644 --- a/test/EFCore.Relational.Specification.Tests/Query/GearsOfWarFromSqlQueryTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/Query/GearsOfWarFromSqlQueryTestBase.cs @@ -6,8 +6,6 @@ // ReSharper disable InconsistentNaming namespace Microsoft.EntityFrameworkCore.Query; -#nullable disable - public abstract class GearsOfWarFromSqlQueryTestBase(TFixture fixture) : IClassFixture where TFixture : GearsOfWarQueryRelationalFixture, new() { diff --git a/test/EFCore.Relational.Specification.Tests/Query/GearsOfWarQueryRelationalFixture.cs b/test/EFCore.Relational.Specification.Tests/Query/GearsOfWarQueryRelationalFixture.cs index 4606fbc6515..6698311f689 100644 --- a/test/EFCore.Relational.Specification.Tests/Query/GearsOfWarQueryRelationalFixture.cs +++ b/test/EFCore.Relational.Specification.Tests/Query/GearsOfWarQueryRelationalFixture.cs @@ -5,13 +5,11 @@ namespace Microsoft.EntityFrameworkCore.Query; -#nullable disable - public abstract class GearsOfWarQueryRelationalFixture : GearsOfWarQueryFixtureBase, ITestSqlLoggerFactory { - public override Dictionary<(Type, string), Func> GetShadowPropertyMappings() + public override Dictionary<(Type, string), Func> GetShadowPropertyMappings() { - var discriminatorMapping = new Dictionary<(Type, string), Func> + var discriminatorMapping = new Dictionary<(Type, string), Func> { { (typeof(Gear), "Discriminator"), e => (((Gear)e)?.Nickname)switch diff --git a/test/EFCore.Relational.Specification.Tests/Query/GearsOfWarQueryRelationalTestBase.cs b/test/EFCore.Relational.Specification.Tests/Query/GearsOfWarQueryRelationalTestBase.cs index b38d58a5996..2d962111efa 100644 --- a/test/EFCore.Relational.Specification.Tests/Query/GearsOfWarQueryRelationalTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/Query/GearsOfWarQueryRelationalTestBase.cs @@ -6,8 +6,6 @@ namespace Microsoft.EntityFrameworkCore.Query; -#nullable disable - public abstract class GearsOfWarQueryRelationalTestBase(TFixture fixture) : GearsOfWarQueryTestBase(fixture) where TFixture : GearsOfWarQueryFixtureBase, new() { diff --git a/test/EFCore.Relational.Specification.Tests/Query/Inheritance/TPCFiltersInheritanceQueryTestBase.cs b/test/EFCore.Relational.Specification.Tests/Query/Inheritance/TPCFiltersInheritanceQueryTestBase.cs index ef4b349ae89..2974675d525 100644 --- a/test/EFCore.Relational.Specification.Tests/Query/Inheritance/TPCFiltersInheritanceQueryTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/Query/Inheritance/TPCFiltersInheritanceQueryTestBase.cs @@ -3,7 +3,5 @@ namespace Microsoft.EntityFrameworkCore.Query.Inheritance; -#nullable disable - public abstract class TPCFiltersInheritanceQueryTestBase(TFixture fixture) : FiltersInheritanceQueryTestBase(fixture) where TFixture : TPCInheritanceQueryFixture, new(); diff --git a/test/EFCore.Relational.Specification.Tests/Query/Inheritance/TPCGearsOfWarQueryRelationalFixture.cs b/test/EFCore.Relational.Specification.Tests/Query/Inheritance/TPCGearsOfWarQueryRelationalFixture.cs index 77fb8efc613..cdd4dcaeab1 100644 --- a/test/EFCore.Relational.Specification.Tests/Query/Inheritance/TPCGearsOfWarQueryRelationalFixture.cs +++ b/test/EFCore.Relational.Specification.Tests/Query/Inheritance/TPCGearsOfWarQueryRelationalFixture.cs @@ -5,8 +5,6 @@ namespace Microsoft.EntityFrameworkCore.Query.Inheritance; -#nullable disable - public abstract class TPCGearsOfWarQueryRelationalFixture : GearsOfWarQueryFixtureBase, ITestSqlLoggerFactory { protected override string StoreName diff --git a/test/EFCore.Relational.Specification.Tests/Query/Inheritance/TPCGearsOfWarQueryRelationalTestBase.cs b/test/EFCore.Relational.Specification.Tests/Query/Inheritance/TPCGearsOfWarQueryRelationalTestBase.cs index 9898818373b..e56146557a6 100644 --- a/test/EFCore.Relational.Specification.Tests/Query/Inheritance/TPCGearsOfWarQueryRelationalTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/Query/Inheritance/TPCGearsOfWarQueryRelationalTestBase.cs @@ -3,8 +3,6 @@ namespace Microsoft.EntityFrameworkCore.Query.Inheritance; -#nullable disable - public abstract class TPCGearsOfWarQueryRelationalTestBase(TFixture fixture) : GearsOfWarQueryRelationalTestBase(fixture) where TFixture : TPCGearsOfWarQueryRelationalFixture, new() diff --git a/test/EFCore.Relational.Specification.Tests/Query/Inheritance/TPCInheritanceQueryFixture.cs b/test/EFCore.Relational.Specification.Tests/Query/Inheritance/TPCInheritanceQueryFixture.cs index 1245b356f4f..4d7d0fa81c7 100644 --- a/test/EFCore.Relational.Specification.Tests/Query/Inheritance/TPCInheritanceQueryFixture.cs +++ b/test/EFCore.Relational.Specification.Tests/Query/Inheritance/TPCInheritanceQueryFixture.cs @@ -5,8 +5,6 @@ namespace Microsoft.EntityFrameworkCore.Query.Inheritance; -#nullable disable - public abstract class TPCInheritanceQueryFixture : InheritanceQueryRelationalFixtureBase { protected override string StoreName diff --git a/test/EFCore.Relational.Specification.Tests/Query/Inheritance/TPCInheritanceQueryTestBase.cs b/test/EFCore.Relational.Specification.Tests/Query/Inheritance/TPCInheritanceQueryTestBase.cs index 79278f52c9f..80a069e99b1 100644 --- a/test/EFCore.Relational.Specification.Tests/Query/Inheritance/TPCInheritanceQueryTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/Query/Inheritance/TPCInheritanceQueryTestBase.cs @@ -5,8 +5,6 @@ namespace Microsoft.EntityFrameworkCore.Query.Inheritance; -#nullable disable - public abstract class TPCInheritanceQueryTestBase : InheritanceQueryTestBase where TFixture : TPCInheritanceQueryFixture, new() { diff --git a/test/EFCore.Relational.Specification.Tests/Query/Inheritance/TPCManyToManyNoTrackingQueryRelationalTestBase.cs b/test/EFCore.Relational.Specification.Tests/Query/Inheritance/TPCManyToManyNoTrackingQueryRelationalTestBase.cs index dca8a741bf4..c47491f7f24 100644 --- a/test/EFCore.Relational.Specification.Tests/Query/Inheritance/TPCManyToManyNoTrackingQueryRelationalTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/Query/Inheritance/TPCManyToManyNoTrackingQueryRelationalTestBase.cs @@ -3,8 +3,6 @@ namespace Microsoft.EntityFrameworkCore.Query.Inheritance; -#nullable disable - public abstract class TPCManyToManyNoTrackingQueryRelationalTestBase(TFixture fixture) : ManyToManyNoTrackingQueryRelationalTestBase(fixture) where TFixture : TPCManyToManyQueryRelationalFixture, new(); diff --git a/test/EFCore.Relational.Specification.Tests/Query/Inheritance/TPCManyToManyQueryRelationalFixture.cs b/test/EFCore.Relational.Specification.Tests/Query/Inheritance/TPCManyToManyQueryRelationalFixture.cs index 7a0b279df15..32acc27e362 100644 --- a/test/EFCore.Relational.Specification.Tests/Query/Inheritance/TPCManyToManyQueryRelationalFixture.cs +++ b/test/EFCore.Relational.Specification.Tests/Query/Inheritance/TPCManyToManyQueryRelationalFixture.cs @@ -5,8 +5,6 @@ namespace Microsoft.EntityFrameworkCore.Query.Inheritance; -#nullable disable - public abstract class TPCManyToManyQueryRelationalFixture : ManyToManyQueryRelationalFixture { protected override string StoreName diff --git a/test/EFCore.Relational.Specification.Tests/Query/Inheritance/TPCManyToManyQueryRelationalTestBase.cs b/test/EFCore.Relational.Specification.Tests/Query/Inheritance/TPCManyToManyQueryRelationalTestBase.cs index 8377882be15..bb52f127078 100644 --- a/test/EFCore.Relational.Specification.Tests/Query/Inheritance/TPCManyToManyQueryRelationalTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/Query/Inheritance/TPCManyToManyQueryRelationalTestBase.cs @@ -3,8 +3,6 @@ namespace Microsoft.EntityFrameworkCore.Query.Inheritance; -#nullable disable - public abstract class TPCManyToManyQueryRelationalTestBase(TFixture fixture) : ManyToManyQueryRelationalTestBase(fixture) where TFixture : TPCManyToManyQueryRelationalFixture, new(); diff --git a/test/EFCore.Relational.Specification.Tests/Query/Inheritance/TPCRelationshipsQueryRelationalFixture.cs b/test/EFCore.Relational.Specification.Tests/Query/Inheritance/TPCRelationshipsQueryRelationalFixture.cs index 1ee78fe8100..1b70c3ef3fe 100644 --- a/test/EFCore.Relational.Specification.Tests/Query/Inheritance/TPCRelationshipsQueryRelationalFixture.cs +++ b/test/EFCore.Relational.Specification.Tests/Query/Inheritance/TPCRelationshipsQueryRelationalFixture.cs @@ -5,8 +5,6 @@ namespace Microsoft.EntityFrameworkCore.Query.Inheritance; -#nullable disable - public abstract class TPCRelationshipsQueryRelationalFixture : InheritanceRelationshipsQueryRelationalFixture { protected override string StoreName diff --git a/test/EFCore.Relational.Specification.Tests/Query/Inheritance/TPCRelationshipsQueryTestBase.cs b/test/EFCore.Relational.Specification.Tests/Query/Inheritance/TPCRelationshipsQueryTestBase.cs index c11cf401c5c..3c8c0eea0e4 100644 --- a/test/EFCore.Relational.Specification.Tests/Query/Inheritance/TPCRelationshipsQueryTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/Query/Inheritance/TPCRelationshipsQueryTestBase.cs @@ -3,8 +3,6 @@ namespace Microsoft.EntityFrameworkCore.Query.Inheritance; -#nullable disable - public abstract class TPCRelationshipsQueryTestBase(TFixture fixture) : InheritanceRelationshipsQueryRelationalTestBase(fixture) where TFixture : TPCRelationshipsQueryRelationalFixture, new(); diff --git a/test/EFCore.Relational.Specification.Tests/Query/Inheritance/TPHInheritanceQueryFixture.cs b/test/EFCore.Relational.Specification.Tests/Query/Inheritance/TPHInheritanceQueryFixture.cs index 8c059385941..246bed2c087 100644 --- a/test/EFCore.Relational.Specification.Tests/Query/Inheritance/TPHInheritanceQueryFixture.cs +++ b/test/EFCore.Relational.Specification.Tests/Query/Inheritance/TPHInheritanceQueryFixture.cs @@ -5,8 +5,6 @@ namespace Microsoft.EntityFrameworkCore.Query.Inheritance; -#nullable disable - public abstract class TPHInheritanceQueryFixture : InheritanceQueryRelationalFixtureBase { protected override void OnModelCreating(ModelBuilder modelBuilder, DbContext context) diff --git a/test/EFCore.Relational.Specification.Tests/Query/Inheritance/TPHInheritanceQueryTestBase.cs b/test/EFCore.Relational.Specification.Tests/Query/Inheritance/TPHInheritanceQueryTestBase.cs index 8bd365e68e7..447ab648887 100644 --- a/test/EFCore.Relational.Specification.Tests/Query/Inheritance/TPHInheritanceQueryTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/Query/Inheritance/TPHInheritanceQueryTestBase.cs @@ -5,8 +5,6 @@ namespace Microsoft.EntityFrameworkCore.Query.Inheritance; -#nullable disable - public abstract class TPHInheritanceQueryTestBase : InheritanceQueryTestBase where TFixture : TPHInheritanceQueryFixture, new() { diff --git a/test/EFCore.Relational.Specification.Tests/Query/Inheritance/TPTFiltersInheritanceQueryTestBase.cs b/test/EFCore.Relational.Specification.Tests/Query/Inheritance/TPTFiltersInheritanceQueryTestBase.cs index 9f36ff89e0a..a737850316c 100644 --- a/test/EFCore.Relational.Specification.Tests/Query/Inheritance/TPTFiltersInheritanceQueryTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/Query/Inheritance/TPTFiltersInheritanceQueryTestBase.cs @@ -3,7 +3,5 @@ namespace Microsoft.EntityFrameworkCore.Query.Inheritance; -#nullable disable - public abstract class TPTFiltersInheritanceQueryTestBase(TFixture fixture) : FiltersInheritanceQueryTestBase(fixture) where TFixture : TPTInheritanceQueryFixture, new(); diff --git a/test/EFCore.Relational.Specification.Tests/Query/Inheritance/TPTGearsOfWarQueryRelationalFixture.cs b/test/EFCore.Relational.Specification.Tests/Query/Inheritance/TPTGearsOfWarQueryRelationalFixture.cs index 36e08663831..09088e7e565 100644 --- a/test/EFCore.Relational.Specification.Tests/Query/Inheritance/TPTGearsOfWarQueryRelationalFixture.cs +++ b/test/EFCore.Relational.Specification.Tests/Query/Inheritance/TPTGearsOfWarQueryRelationalFixture.cs @@ -5,8 +5,6 @@ namespace Microsoft.EntityFrameworkCore.Query.Inheritance; -#nullable disable - public abstract class TPTGearsOfWarQueryRelationalFixture : GearsOfWarQueryFixtureBase, ITestSqlLoggerFactory { protected override string StoreName diff --git a/test/EFCore.Relational.Specification.Tests/Query/Inheritance/TPTGearsOfWarQueryRelationalTestBase.cs b/test/EFCore.Relational.Specification.Tests/Query/Inheritance/TPTGearsOfWarQueryRelationalTestBase.cs index 773caea6aec..b1d2e46c254 100644 --- a/test/EFCore.Relational.Specification.Tests/Query/Inheritance/TPTGearsOfWarQueryRelationalTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/Query/Inheritance/TPTGearsOfWarQueryRelationalTestBase.cs @@ -3,8 +3,6 @@ namespace Microsoft.EntityFrameworkCore.Query.Inheritance; -#nullable disable - public abstract class TPTGearsOfWarQueryRelationalTestBase(TFixture fixture) : GearsOfWarQueryRelationalTestBase(fixture) where TFixture : TPTGearsOfWarQueryRelationalFixture, new() diff --git a/test/EFCore.Relational.Specification.Tests/Query/Inheritance/TPTInheritanceQueryFixture.cs b/test/EFCore.Relational.Specification.Tests/Query/Inheritance/TPTInheritanceQueryFixture.cs index 98806664cde..cc667436b6a 100644 --- a/test/EFCore.Relational.Specification.Tests/Query/Inheritance/TPTInheritanceQueryFixture.cs +++ b/test/EFCore.Relational.Specification.Tests/Query/Inheritance/TPTInheritanceQueryFixture.cs @@ -5,8 +5,6 @@ namespace Microsoft.EntityFrameworkCore.Query.Inheritance; -#nullable disable - public abstract class TPTInheritanceQueryFixture : InheritanceQueryRelationalFixtureBase { protected override string StoreName diff --git a/test/EFCore.Relational.Specification.Tests/Query/Inheritance/TPTInheritanceQueryTestBase.cs b/test/EFCore.Relational.Specification.Tests/Query/Inheritance/TPTInheritanceQueryTestBase.cs index 4fc0aff5060..b57837ed9c6 100644 --- a/test/EFCore.Relational.Specification.Tests/Query/Inheritance/TPTInheritanceQueryTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/Query/Inheritance/TPTInheritanceQueryTestBase.cs @@ -5,8 +5,6 @@ namespace Microsoft.EntityFrameworkCore.Query.Inheritance; -#nullable disable - public abstract class TPTInheritanceQueryTestBase : InheritanceQueryTestBase where TFixture : TPTInheritanceQueryFixture, new() { diff --git a/test/EFCore.Relational.Specification.Tests/Query/Inheritance/TPTManyToManyNoTrackingQueryRelationalTestBase.cs b/test/EFCore.Relational.Specification.Tests/Query/Inheritance/TPTManyToManyNoTrackingQueryRelationalTestBase.cs index 9854329a004..f975ceef21e 100644 --- a/test/EFCore.Relational.Specification.Tests/Query/Inheritance/TPTManyToManyNoTrackingQueryRelationalTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/Query/Inheritance/TPTManyToManyNoTrackingQueryRelationalTestBase.cs @@ -3,8 +3,6 @@ namespace Microsoft.EntityFrameworkCore.Query.Inheritance; -#nullable disable - public abstract class TPTManyToManyNoTrackingQueryRelationalTestBase(TFixture fixture) : ManyToManyNoTrackingQueryRelationalTestBase(fixture) where TFixture : TPTManyToManyQueryRelationalFixture, new(); diff --git a/test/EFCore.Relational.Specification.Tests/Query/Inheritance/TPTManyToManyQueryRelationalFixture.cs b/test/EFCore.Relational.Specification.Tests/Query/Inheritance/TPTManyToManyQueryRelationalFixture.cs index 90dce0727f2..6428593fafa 100644 --- a/test/EFCore.Relational.Specification.Tests/Query/Inheritance/TPTManyToManyQueryRelationalFixture.cs +++ b/test/EFCore.Relational.Specification.Tests/Query/Inheritance/TPTManyToManyQueryRelationalFixture.cs @@ -5,8 +5,6 @@ namespace Microsoft.EntityFrameworkCore.Query.Inheritance; -#nullable disable - public abstract class TPTManyToManyQueryRelationalFixture : ManyToManyQueryRelationalFixture { protected override string StoreName diff --git a/test/EFCore.Relational.Specification.Tests/Query/Inheritance/TPTManyToManyQueryRelationalTestBase.cs b/test/EFCore.Relational.Specification.Tests/Query/Inheritance/TPTManyToManyQueryRelationalTestBase.cs index 04e63bc233e..cecad9d2215 100644 --- a/test/EFCore.Relational.Specification.Tests/Query/Inheritance/TPTManyToManyQueryRelationalTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/Query/Inheritance/TPTManyToManyQueryRelationalTestBase.cs @@ -3,8 +3,6 @@ namespace Microsoft.EntityFrameworkCore.Query.Inheritance; -#nullable disable - public abstract class TPTManyToManyQueryRelationalTestBase(TFixture fixture) : ManyToManyQueryRelationalTestBase(fixture) where TFixture : TPTManyToManyQueryRelationalFixture, new(); diff --git a/test/EFCore.Relational.Specification.Tests/Query/Inheritance/TPTRelationshipsQueryRelationalFixture.cs b/test/EFCore.Relational.Specification.Tests/Query/Inheritance/TPTRelationshipsQueryRelationalFixture.cs index 0c8cdd2b51d..68d4ebeb219 100644 --- a/test/EFCore.Relational.Specification.Tests/Query/Inheritance/TPTRelationshipsQueryRelationalFixture.cs +++ b/test/EFCore.Relational.Specification.Tests/Query/Inheritance/TPTRelationshipsQueryRelationalFixture.cs @@ -5,8 +5,6 @@ namespace Microsoft.EntityFrameworkCore.Query.Inheritance; -#nullable disable - public abstract class TPTRelationshipsQueryRelationalFixture : InheritanceRelationshipsQueryRelationalFixture { protected override string StoreName diff --git a/test/EFCore.Relational.Specification.Tests/Query/Inheritance/TPTRelationshipsQueryTestBase.cs b/test/EFCore.Relational.Specification.Tests/Query/Inheritance/TPTRelationshipsQueryTestBase.cs index 5a55d5c98b2..dfe4c00e61d 100644 --- a/test/EFCore.Relational.Specification.Tests/Query/Inheritance/TPTRelationshipsQueryTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/Query/Inheritance/TPTRelationshipsQueryTestBase.cs @@ -5,8 +5,6 @@ namespace Microsoft.EntityFrameworkCore.Query.Inheritance; -#nullable disable - public abstract class TPTRelationshipsQueryTestBase(TFixture fixture) : InheritanceRelationshipsQueryRelationalTestBase(fixture) where TFixture : TPTRelationshipsQueryRelationalFixture, new(); diff --git a/test/EFCore.Relational.Specification.Tests/Query/InheritanceRelationshipsQueryRelationalFixture.cs b/test/EFCore.Relational.Specification.Tests/Query/InheritanceRelationshipsQueryRelationalFixture.cs index d3ed73c11ad..1760a9e60b4 100644 --- a/test/EFCore.Relational.Specification.Tests/Query/InheritanceRelationshipsQueryRelationalFixture.cs +++ b/test/EFCore.Relational.Specification.Tests/Query/InheritanceRelationshipsQueryRelationalFixture.cs @@ -3,8 +3,6 @@ namespace Microsoft.EntityFrameworkCore.Query; -#nullable disable - public abstract class InheritanceRelationshipsQueryRelationalFixture : InheritanceRelationshipsQueryFixtureBase, ITestSqlLoggerFactory { public TestSqlLoggerFactory TestSqlLoggerFactory diff --git a/test/EFCore.Relational.Specification.Tests/Query/InheritanceRelationshipsQueryRelationalTestBase.cs b/test/EFCore.Relational.Specification.Tests/Query/InheritanceRelationshipsQueryRelationalTestBase.cs index bb466c1699f..e8df28f2f74 100644 --- a/test/EFCore.Relational.Specification.Tests/Query/InheritanceRelationshipsQueryRelationalTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/Query/InheritanceRelationshipsQueryRelationalTestBase.cs @@ -5,8 +5,6 @@ namespace Microsoft.EntityFrameworkCore.Query; -#nullable disable - public abstract class InheritanceRelationshipsQueryRelationalTestBase(TFixture fixture) : InheritanceRelationshipsQueryTestBase(fixture) where TFixture : InheritanceRelationshipsQueryRelationalFixture, new() @@ -27,7 +25,7 @@ public virtual Task Include_collection_with_inheritance_reverse_split(bool async ss => ss.Set().Include(e => e.BaseParent).AsSplitQuery(), elementAsserter: (e, a) => AssertInclude( e, a, - new ExpectedInclude(x => x.BaseParent))); + new ExpectedInclude(x => x.BaseParent!))); [Theory, MemberData(nameof(IsAsyncData))] public virtual Task Include_collection_with_inheritance_with_filter_split(bool async) @@ -46,7 +44,7 @@ public virtual Task Include_collection_with_inheritance_with_filter_reverse_spli ss => ss.Set().Include(e => e.BaseParent).Where(e => e.Name != "Bar").AsSplitQuery(), elementAsserter: (e, a) => AssertInclude( e, a, - new ExpectedInclude(x => x.BaseParent))); + new ExpectedInclude(x => x.BaseParent!))); [Theory, MemberData(nameof(IsAsyncData))] public virtual Task Include_collection_without_inheritance_split(bool async) @@ -64,7 +62,7 @@ public virtual Task Include_collection_without_inheritance_reverse_split(bool as ss => ss.Set().Include(e => e.Parent).AsSplitQuery(), elementAsserter: (e, a) => AssertInclude( e, a, - new ExpectedInclude(x => x.Parent))); + new ExpectedInclude(x => x.Parent!))); [Theory, MemberData(nameof(IsAsyncData))] public virtual Task Include_collection_without_inheritance_with_filter_split(bool async) @@ -83,7 +81,7 @@ public virtual Task Include_collection_without_inheritance_with_filter_reverse_s ss => ss.Set().Include(e => e.Parent).Where(e => e.Name != "Bar").AsSplitQuery(), elementAsserter: (e, a) => AssertInclude( e, a, - new ExpectedInclude(x => x.Parent))); + new ExpectedInclude(x => x.Parent!))); [Theory, MemberData(nameof(IsAsyncData))] public virtual Task Include_collection_with_inheritance_on_derived1_split(bool async) @@ -119,37 +117,37 @@ public virtual Task Include_collection_with_inheritance_on_derived_reverse_split ss => ss.Set().Include(e => e.BaseParent).AsSplitQuery(), elementAsserter: (e, a) => AssertInclude( e, a, - new ExpectedInclude(x => x.BaseParent))); + new ExpectedInclude(x => x.BaseParent!))); [Theory, MemberData(nameof(IsAsyncData))] public virtual Task Nested_include_with_inheritance_reference_collection_split(bool async) => AssertQuery( async, - ss => ss.Set().Include(e => e.BaseReferenceOnBase.NestedCollection).AsSplitQuery(), + ss => ss.Set().Include(e => e.BaseReferenceOnBase!.NestedCollection).AsSplitQuery(), elementAsserter: (e, a) => AssertInclude( e, a, - new ExpectedInclude(x => x.BaseReferenceOnBase), + new ExpectedInclude(x => x.BaseReferenceOnBase!), new ExpectedInclude(x => x.NestedCollection))); [Theory, MemberData(nameof(IsAsyncData))] public virtual Task Nested_include_with_inheritance_reference_collection_on_base_split(bool async) => AssertQuery( async, - ss => ss.Set().Include(e => e.BaseReferenceOnBase.NestedCollection).AsSplitQuery(), + ss => ss.Set().Include(e => e.BaseReferenceOnBase!.NestedCollection).AsSplitQuery(), elementAsserter: (e, a) => AssertInclude( e, a, - new ExpectedInclude(x => x.BaseReferenceOnBase), + new ExpectedInclude(x => x.BaseReferenceOnBase!), new ExpectedInclude(x => x.NestedCollection))); [Theory, MemberData(nameof(IsAsyncData))] public virtual Task Nested_include_with_inheritance_reference_collection_reverse_split(bool async) => AssertQuery( async, - ss => ss.Set().Include(e => e.ParentReference.BaseParent).AsSplitQuery(), + ss => ss.Set().Include(e => e.ParentReference!.BaseParent).AsSplitQuery(), elementAsserter: (e, a) => AssertInclude( e, a, - new ExpectedInclude(x => x.ParentReference), - new ExpectedInclude(x => x.BaseParent))); + new ExpectedInclude(x => x.ParentReference!), + new ExpectedInclude(x => x.BaseParent!))); [Theory, MemberData(nameof(IsAsyncData))] public virtual Task Nested_include_with_inheritance_collection_reference_split(bool async) @@ -160,17 +158,17 @@ public virtual Task Nested_include_with_inheritance_collection_reference_split(b elementAsserter: (e, a) => AssertInclude( e, a, new ExpectedInclude(x => x.BaseCollectionOnBase), - new ExpectedInclude(x => x.NestedReference))); + new ExpectedInclude(x => x.NestedReference!))); [Theory, MemberData(nameof(IsAsyncData))] public virtual Task Nested_include_with_inheritance_collection_reference_reverse_split(bool async) => AssertQuery( async, - ss => ss.Set().Include(e => e.ParentCollection.BaseParent).AsSplitQuery(), + ss => ss.Set().Include(e => e.ParentCollection!.BaseParent).AsSplitQuery(), elementAsserter: (e, a) => AssertInclude( e, a, - new ExpectedInclude(x => x.ParentCollection), - new ExpectedInclude(x => x.BaseParent))); + new ExpectedInclude(x => x.ParentCollection!), + new ExpectedInclude(x => x.BaseParent!))); [Theory, MemberData(nameof(IsAsyncData))] public virtual Task Nested_include_with_inheritance_collection_collection_split(bool async) @@ -187,11 +185,11 @@ public virtual Task Nested_include_with_inheritance_collection_collection_split( public virtual Task Nested_include_with_inheritance_collection_collection_reverse_split(bool async) => AssertQuery( async, - ss => ss.Set().Include(e => e.ParentCollection.BaseParent).AsSplitQuery(), + ss => ss.Set().Include(e => e.ParentCollection!.BaseParent).AsSplitQuery(), elementAsserter: (e, a) => AssertInclude( e, a, - new ExpectedInclude(x => x.ParentCollection), - new ExpectedInclude(x => x.BaseParent))); + new ExpectedInclude(x => x.ParentCollection!), + new ExpectedInclude(x => x.BaseParent!))); [Theory, MemberData(nameof(IsAsyncData))] public virtual Task Nested_include_collection_reference_on_non_entity_base_split(bool async) @@ -201,7 +199,7 @@ public virtual Task Nested_include_collection_reference_on_non_entity_base_split elementAsserter: (e, a) => AssertInclude( e, a, new ExpectedInclude(x => x.Principals), - new ExpectedInclude(x => x.Reference))); + new ExpectedInclude(x => x.Reference!))); [Theory, MemberData(nameof(IsAsyncData))] public virtual Task Collection_projection_on_base_type_split(bool async) diff --git a/test/EFCore.Relational.Specification.Tests/Query/JsonQueryRelationalFixture.cs b/test/EFCore.Relational.Specification.Tests/Query/JsonQueryRelationalFixture.cs index ad0c6402677..3d0922738d3 100644 --- a/test/EFCore.Relational.Specification.Tests/Query/JsonQueryRelationalFixture.cs +++ b/test/EFCore.Relational.Specification.Tests/Query/JsonQueryRelationalFixture.cs @@ -5,8 +5,6 @@ namespace Microsoft.EntityFrameworkCore.Query; -#nullable disable - public abstract class JsonQueryRelationalFixture : JsonQueryFixtureBase, ITestSqlLoggerFactory { public new RelationalTestStore TestStore diff --git a/test/EFCore.Relational.Specification.Tests/Query/JsonQueryRelationalTestBase.cs b/test/EFCore.Relational.Specification.Tests/Query/JsonQueryRelationalTestBase.cs index f3180abe0a6..232ddd7b2f0 100644 --- a/test/EFCore.Relational.Specification.Tests/Query/JsonQueryRelationalTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/Query/JsonQueryRelationalTestBase.cs @@ -440,7 +440,7 @@ public virtual async Task Json_projection_deduplication_with_collection_indexer_ x.Id, Duplicate1 = x.OwnedReferenceRoot.OwnedCollectionBranch[1], Original = x.OwnedReferenceRoot, - Duplicate2 = x.OwnedReferenceRoot.OwnedReferenceBranch.OwnedCollectionLeaf[prm] + Duplicate2 = x.OwnedReferenceRoot.OwnedReferenceBranch!.OwnedCollectionLeaf[prm] }).AsNoTrackingWithIdentityResolution(), elementSorter: e => e.Id, elementAsserter: (e, a) => @@ -549,7 +549,7 @@ public virtual async Task Json_projection_second_element_projected_before_owner_ ss => ss.Set().Select(x => new { x.Id, - Duplicate = x.OwnedReferenceRoot.OwnedReferenceBranch.OwnedCollectionLeaf[1], + Duplicate = x.OwnedReferenceRoot.OwnedReferenceBranch!.OwnedCollectionLeaf[1], Original = x.OwnedReferenceRoot.OwnedReferenceBranch.OwnedCollectionLeaf, Parent = x.OwnedReferenceRoot.OwnedReferenceBranch, }).AsNoTrackingWithIdentityResolution(), @@ -570,9 +570,6 @@ public virtual async Task Json_projection_second_element_projected_before_owner_ #region Non-shared test resources -#nullable disable - - protected override void ConfigureWarnings(WarningsConfigurationBuilder builder) { base.ConfigureWarnings(builder); @@ -583,7 +580,7 @@ protected override void ConfigureWarnings(WarningsConfigurationBuilder builder) protected TestSqlLoggerFactory TestSqlLoggerFactory => (TestSqlLoggerFactory)ListLoggerFactory; - protected virtual string JsonColumnType + protected virtual string? JsonColumnType => null; #region 21006 @@ -751,30 +748,31 @@ public virtual async Task Project_optional_json_entity_owned_by_required_json_en protected class Context34293(DbContextOptions options) : DbContext(options) { - public DbSet Entities { get; set; } + public DbSet Entities + => Set(); public class Entity { public int Id { get; set; } - public JsonRoot Json { get; set; } + public JsonRoot Json { get; set; } = null!; } public class JsonRoot { public DateTime Date { get; set; } - public JsonBranch Required { get; set; } + public JsonBranch Required { get; set; } = null!; } public class JsonBranch { public int Number { get; set; } - public JsonLeaf Optional { get; set; } + public JsonLeaf? Optional { get; set; } } public class JsonLeaf { - public string Name { get; set; } + public string Name { get; set; } = null!; } public async Task Seed() @@ -804,7 +802,7 @@ public async Task Seed() Json = new JsonRoot { Date = new DateTime(2003, 3, 3), - Required = null, + Required = null!, } }; @@ -1128,15 +1126,15 @@ protected class ContextEntitySplitting(DbContextOptions options) : DbContext(opt public class MyEntity { public int Id { get; set; } - public string PropertyInMainTable { get; set; } // TODO: currently required because of #36171 - public string PropertyInOtherTable { get; set; } + public string? PropertyInMainTable { get; set; } + public string PropertyInOtherTable { get; set; } = null!; - public List Json { get; set; } + public List Json { get; set; } = null!; } public class JsonEntity { - public string Foo { get; set; } + public string Foo { get; set; } = null!; } } @@ -1195,20 +1193,21 @@ public virtual async Task HasJsonPropertyName() protected class Context37009(DbContextOptions options) : DbContext(options) { - public DbSet Entities { get; set; } + public DbSet Entities + => Set(); public class Entity { public int Id { get; set; } - public JsonComplexType Json { get; set; } + public JsonComplexType Json { get; set; } = null!; } public class JsonComplexType { - public string String { get; set; } + public string String { get; set; } = null!; - public JsonNestedType Nested { get; set; } - public List NestedCollection { get; set; } + public JsonNestedType Nested { get; set; } = null!; + public List NestedCollection { get; set; } = null!; } public class JsonNestedType @@ -1294,21 +1293,21 @@ protected class Context38615(DbContextOptions options) : DbContext(options) public class Car { public int CarId { get; set; } - public string Vin { get; set; } - public string DealerId { get; set; } - public CarConfiguration CarConfiguration { get; set; } + public string Vin { get; set; } = null!; + public string DealerId { get; set; } = null!; + public CarConfiguration CarConfiguration { get; set; } = null!; } public class CarConfiguration { - public string CurrentTrim { get; set; } - public List OptionPackages { get; set; } + public string CurrentTrim { get; set; } = null!; + public List OptionPackages { get; set; } = null!; } public class OptionPackage { - public string PackageId { get; set; } - public ICollection PartNumbers { get; set; } + public string PackageId { get; set; } = null!; + public ICollection PartNumbers { get; set; } = null!; } } @@ -1347,12 +1346,13 @@ public virtual async Task Value_converter_equality_null_scalar() protected class Context37983(DbContextOptions options) : DbContext(options) { - public DbSet Entities { get; set; } + public DbSet Entities + => Set(); public class Entity { public int Id { get; set; } - public JsonComplexType Json { get; set; } + public JsonComplexType Json { get; set; } = null!; } public class JsonComplexType @@ -1365,8 +1365,8 @@ protected class Context37983_StringToIntConverter : ValueConverter { public Context37983_StringToIntConverter() : base( - v => v == null ? "" : v.ToString(), - v => int.Parse(v)) + v => v == null ? "" : v.ToString()!, + v => int.Parse(v!)) { } @@ -1422,8 +1422,11 @@ string Q(string name) protected class Context38315(DbContextOptions options) : DbContext(options) { - public DbSet Persons { get; set; } - public DbSet PersonOrdersViews { get; set; } + public DbSet Persons + => Set(); + + public DbSet PersonOrdersViews + => Set(); public class Person { @@ -1445,7 +1448,5 @@ public class ValueJson #endregion -#nullable restore - #endregion } diff --git a/test/EFCore.Relational.Specification.Tests/Query/ManyToManyNoTrackingQueryRelationalTestBase.cs b/test/EFCore.Relational.Specification.Tests/Query/ManyToManyNoTrackingQueryRelationalTestBase.cs index 52d87d37a89..609401b904e 100644 --- a/test/EFCore.Relational.Specification.Tests/Query/ManyToManyNoTrackingQueryRelationalTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/Query/ManyToManyNoTrackingQueryRelationalTestBase.cs @@ -5,8 +5,6 @@ namespace Microsoft.EntityFrameworkCore.Query; -#nullable disable - public abstract class ManyToManyNoTrackingQueryRelationalTestBase(TFixture fixture) : ManyToManyNoTrackingQueryTestBase(fixture) where TFixture : ManyToManyQueryFixtureBase, new() diff --git a/test/EFCore.Relational.Specification.Tests/Query/ManyToManyQueryRelationalFixture.cs b/test/EFCore.Relational.Specification.Tests/Query/ManyToManyQueryRelationalFixture.cs index f0c486f59ae..0e1b4cae07e 100644 --- a/test/EFCore.Relational.Specification.Tests/Query/ManyToManyQueryRelationalFixture.cs +++ b/test/EFCore.Relational.Specification.Tests/Query/ManyToManyQueryRelationalFixture.cs @@ -5,8 +5,6 @@ namespace Microsoft.EntityFrameworkCore.Query; -#nullable disable - public abstract class ManyToManyQueryRelationalFixture : ManyToManyQueryFixtureBase, ITestSqlLoggerFactory { public TestSqlLoggerFactory TestSqlLoggerFactory diff --git a/test/EFCore.Relational.Specification.Tests/Query/ManyToManyQueryRelationalTestBase.cs b/test/EFCore.Relational.Specification.Tests/Query/ManyToManyQueryRelationalTestBase.cs index 3f001a767ef..6302cf22f3c 100644 --- a/test/EFCore.Relational.Specification.Tests/Query/ManyToManyQueryRelationalTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/Query/ManyToManyQueryRelationalTestBase.cs @@ -5,8 +5,6 @@ namespace Microsoft.EntityFrameworkCore.Query; -#nullable disable - public abstract class ManyToManyQueryRelationalTestBase(TFixture fixture) : ManyToManyQueryTestBase(fixture) where TFixture : ManyToManyQueryFixtureBase, new() { diff --git a/test/EFCore.Relational.Specification.Tests/Query/MappingQueryTestBase.cs b/test/EFCore.Relational.Specification.Tests/Query/MappingQueryTestBase.cs index 54c1ff93853..13d70882d82 100644 --- a/test/EFCore.Relational.Specification.Tests/Query/MappingQueryTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/Query/MappingQueryTestBase.cs @@ -6,8 +6,6 @@ // ReSharper disable InconsistentNaming namespace Microsoft.EntityFrameworkCore.Query; -#nullable disable - public abstract class MappingQueryTestBase(MappingQueryTestBase.MappingQueryFixtureBase fixture) : IClassFixture where TFixture : MappingQueryTestBase.MappingQueryFixtureBase, new() @@ -64,12 +62,12 @@ protected virtual DbContext CreateContext() protected class MappedCustomer : Customer { - public string CompanyName2 { get; set; } + public string CompanyName2 { get; set; } = null!; } protected class MappedEmployee : Employee { - public string City2 { get; set; } + public string? City2 { get; set; } } protected class MappedOrder : Order diff --git a/test/EFCore.Relational.Specification.Tests/Query/NorthwindAggregateOperatorsQueryRelationalTestBase.cs b/test/EFCore.Relational.Specification.Tests/Query/NorthwindAggregateOperatorsQueryRelationalTestBase.cs index 292847f1c46..5fb36f534b5 100644 --- a/test/EFCore.Relational.Specification.Tests/Query/NorthwindAggregateOperatorsQueryRelationalTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/Query/NorthwindAggregateOperatorsQueryRelationalTestBase.cs @@ -5,8 +5,6 @@ namespace Microsoft.EntityFrameworkCore.Query; -#nullable disable - public abstract class NorthwindAggregateOperatorsQueryRelationalTestBase(TFixture fixture) : NorthwindAggregateOperatorsQueryTestBase(fixture) where TFixture : NorthwindQueryFixtureBase, new() diff --git a/test/EFCore.Relational.Specification.Tests/Query/NorthwindFunctionsQueryRelationalTestBase.cs b/test/EFCore.Relational.Specification.Tests/Query/NorthwindFunctionsQueryRelationalTestBase.cs index b70b9a07fc8..c2b7741c001 100644 --- a/test/EFCore.Relational.Specification.Tests/Query/NorthwindFunctionsQueryRelationalTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/Query/NorthwindFunctionsQueryRelationalTestBase.cs @@ -3,8 +3,6 @@ namespace Microsoft.EntityFrameworkCore.Query; -#nullable disable - public abstract class NorthwindFunctionsQueryRelationalTestBase(TFixture fixture) : NorthwindFunctionsQueryTestBase(fixture) where TFixture : NorthwindQueryFixtureBase, new(); diff --git a/test/EFCore.Relational.Specification.Tests/Query/NorthwindGroupByQueryRelationalTestBase.cs b/test/EFCore.Relational.Specification.Tests/Query/NorthwindGroupByQueryRelationalTestBase.cs index 6416b8e677d..b18107443c9 100644 --- a/test/EFCore.Relational.Specification.Tests/Query/NorthwindGroupByQueryRelationalTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/Query/NorthwindGroupByQueryRelationalTestBase.cs @@ -3,7 +3,5 @@ namespace Microsoft.EntityFrameworkCore.Query; -#nullable disable - public abstract class NorthwindGroupByQueryRelationalTestBase(TFixture fixture) : NorthwindGroupByQueryTestBase(fixture) where TFixture : NorthwindQueryFixtureBase, new(); diff --git a/test/EFCore.Relational.Specification.Tests/Query/NorthwindIncludeQueryRelationalTestBase.cs b/test/EFCore.Relational.Specification.Tests/Query/NorthwindIncludeQueryRelationalTestBase.cs index e026d1080bd..7202e6ac9d4 100644 --- a/test/EFCore.Relational.Specification.Tests/Query/NorthwindIncludeQueryRelationalTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/Query/NorthwindIncludeQueryRelationalTestBase.cs @@ -3,8 +3,6 @@ namespace Microsoft.EntityFrameworkCore.Query; -#nullable disable - public abstract class NorthwindIncludeQueryRelationalTestBase(TFixture fixture) : NorthwindIncludeQueryTestBase(fixture) where TFixture : NorthwindQueryFixtureBase, new() { diff --git a/test/EFCore.Relational.Specification.Tests/Query/NorthwindJoinQueryRelationalTestBase.cs b/test/EFCore.Relational.Specification.Tests/Query/NorthwindJoinQueryRelationalTestBase.cs index 0b77d20c6ea..1f83cb0e6e8 100644 --- a/test/EFCore.Relational.Specification.Tests/Query/NorthwindJoinQueryRelationalTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/Query/NorthwindJoinQueryRelationalTestBase.cs @@ -3,7 +3,5 @@ namespace Microsoft.EntityFrameworkCore.Query; -#nullable disable - public abstract class NorthwindJoinQueryRelationalTestBase(TFixture fixture) : NorthwindJoinQueryTestBase(fixture) where TFixture : NorthwindQueryFixtureBase, new(); diff --git a/test/EFCore.Relational.Specification.Tests/Query/NorthwindKeylessEntitiesQueryRelationalTestBase.cs b/test/EFCore.Relational.Specification.Tests/Query/NorthwindKeylessEntitiesQueryRelationalTestBase.cs index 9c096d2ccf2..04a14376e26 100644 --- a/test/EFCore.Relational.Specification.Tests/Query/NorthwindKeylessEntitiesQueryRelationalTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/Query/NorthwindKeylessEntitiesQueryRelationalTestBase.cs @@ -5,8 +5,6 @@ namespace Microsoft.EntityFrameworkCore.Query; -#nullable disable - public abstract class NorthwindKeylessEntitiesQueryRelationalTestBase(TFixture fixture) : NorthwindKeylessEntitiesQueryTestBase(fixture) where TFixture : NorthwindQueryFixtureBase, new() diff --git a/test/EFCore.Relational.Specification.Tests/Query/NorthwindMiscellaneousQueryRelationalTestBase.cs b/test/EFCore.Relational.Specification.Tests/Query/NorthwindMiscellaneousQueryRelationalTestBase.cs index 8447f545bc6..f25209ee558 100644 --- a/test/EFCore.Relational.Specification.Tests/Query/NorthwindMiscellaneousQueryRelationalTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/Query/NorthwindMiscellaneousQueryRelationalTestBase.cs @@ -5,8 +5,6 @@ namespace Microsoft.EntityFrameworkCore.Query; -#nullable disable - public abstract class NorthwindMiscellaneousQueryRelationalTestBase(TFixture fixture) : NorthwindMiscellaneousQueryTestBase(fixture) where TFixture : NorthwindQueryFixtureBase, new() diff --git a/test/EFCore.Relational.Specification.Tests/Query/NorthwindNavigationsQueryRelationalTestBase.cs b/test/EFCore.Relational.Specification.Tests/Query/NorthwindNavigationsQueryRelationalTestBase.cs index f4c066e3780..64b2a935989 100644 --- a/test/EFCore.Relational.Specification.Tests/Query/NorthwindNavigationsQueryRelationalTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/Query/NorthwindNavigationsQueryRelationalTestBase.cs @@ -3,8 +3,6 @@ namespace Microsoft.EntityFrameworkCore.Query; -#nullable disable - public abstract class NorthwindNavigationsQueryRelationalTestBase(TFixture fixture) : NorthwindNavigationsQueryTestBase(fixture) where TFixture : NorthwindQueryFixtureBase, new() diff --git a/test/EFCore.Relational.Specification.Tests/Query/NorthwindQueryRelationalFixture.cs b/test/EFCore.Relational.Specification.Tests/Query/NorthwindQueryRelationalFixture.cs index 0b3a75da1c0..deb3640bd70 100644 --- a/test/EFCore.Relational.Specification.Tests/Query/NorthwindQueryRelationalFixture.cs +++ b/test/EFCore.Relational.Specification.Tests/Query/NorthwindQueryRelationalFixture.cs @@ -3,8 +3,6 @@ namespace Microsoft.EntityFrameworkCore.Query; -#nullable disable - public abstract class NorthwindQueryRelationalFixture : NorthwindQueryFixtureBase, ITestSqlLoggerFactory where TModelCustomizer : ITestModelCustomizer, new() { diff --git a/test/EFCore.Relational.Specification.Tests/Query/NorthwindSelectQueryRelationalTestBase.cs b/test/EFCore.Relational.Specification.Tests/Query/NorthwindSelectQueryRelationalTestBase.cs index e6816ed6ca4..4106c550663 100644 --- a/test/EFCore.Relational.Specification.Tests/Query/NorthwindSelectQueryRelationalTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/Query/NorthwindSelectQueryRelationalTestBase.cs @@ -3,8 +3,6 @@ namespace Microsoft.EntityFrameworkCore.Query; -#nullable disable - public abstract class NorthwindSelectQueryRelationalTestBase(TFixture fixture) : NorthwindSelectQueryTestBase(fixture) where TFixture : NorthwindQueryFixtureBase, new() { diff --git a/test/EFCore.Relational.Specification.Tests/Query/NorthwindSetOperationsQueryRelationalTestBase.cs b/test/EFCore.Relational.Specification.Tests/Query/NorthwindSetOperationsQueryRelationalTestBase.cs index c686796a9b6..60d85d1889c 100644 --- a/test/EFCore.Relational.Specification.Tests/Query/NorthwindSetOperationsQueryRelationalTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/Query/NorthwindSetOperationsQueryRelationalTestBase.cs @@ -3,8 +3,6 @@ namespace Microsoft.EntityFrameworkCore.Query; -#nullable disable - public abstract class NorthwindSetOperationsQueryRelationalTestBase(TFixture fixture) : NorthwindSetOperationsQueryTestBase(fixture) where TFixture : NorthwindQueryFixtureBase, new() diff --git a/test/EFCore.Relational.Specification.Tests/Query/NorthwindSplitIncludeNoTrackingQueryTestBase.cs b/test/EFCore.Relational.Specification.Tests/Query/NorthwindSplitIncludeNoTrackingQueryTestBase.cs index aec7b4a2b1b..468d7d42a15 100644 --- a/test/EFCore.Relational.Specification.Tests/Query/NorthwindSplitIncludeNoTrackingQueryTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/Query/NorthwindSplitIncludeNoTrackingQueryTestBase.cs @@ -9,15 +9,13 @@ // ReSharper disable AccessToDisposedClosure namespace Microsoft.EntityFrameworkCore.Query; -#nullable disable - public abstract class NorthwindSplitIncludeNoTrackingQueryTestBase(TFixture fixture) : NorthwindIncludeNoTrackingQueryTestBase(fixture) where TFixture : NorthwindQueryFixtureBase, new() { private static readonly MethodInfo _asSplitIncludeMethodInfo = typeof(RelationalQueryableExtensions) - .GetTypeInfo().GetDeclaredMethod(nameof(RelationalQueryableExtensions.AsSplitQuery)); + .GetTypeInfo().GetDeclaredMethod(nameof(RelationalQueryableExtensions.AsSplitQuery))!; public override async Task Include_closes_reader(bool async) { @@ -39,7 +37,7 @@ public override async Task Include_collection_dependent_already_tracked(bool asy using var context = CreateContext(); var orders = context.Set().Where(o => o.CustomerID == "ALFKI").ToList(); Assert.Equal(6, context.ChangeTracker.Entries().Count()); - Assert.True(orders.All(o => o.Customer.CustomerID == null)); + Assert.True(orders.All(o => o.Customer!.CustomerID == null)); var customer = async @@ -59,7 +57,7 @@ var customer Assert.True(customer.Orders.All(e => ReferenceEquals(e.Customer, customer))); Assert.Equal(6, context.ChangeTracker.Entries().Count()); - Assert.True(orders.All(o => o.Customer.CustomerID == null)); + Assert.True(orders.All(o => o.Customer!.CustomerID == null)); } public override async Task Include_collection_principal_already_tracked(bool async) diff --git a/test/EFCore.Relational.Specification.Tests/Query/NorthwindSplitIncludeQueryTestBase.cs b/test/EFCore.Relational.Specification.Tests/Query/NorthwindSplitIncludeQueryTestBase.cs index eb878df5caa..f2e226d4694 100644 --- a/test/EFCore.Relational.Specification.Tests/Query/NorthwindSplitIncludeQueryTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/Query/NorthwindSplitIncludeQueryTestBase.cs @@ -9,14 +9,12 @@ // ReSharper disable AccessToDisposedClosure namespace Microsoft.EntityFrameworkCore.Query; -#nullable disable - public abstract class NorthwindSplitIncludeQueryTestBase(TFixture fixture) : NorthwindIncludeQueryTestBase(fixture) where TFixture : NorthwindQueryFixtureBase, new() { private static readonly MethodInfo _asSplitIncludeMethodInfo = typeof(RelationalQueryableExtensions) - .GetTypeInfo().GetDeclaredMethod(nameof(RelationalQueryableExtensions.AsSplitQuery)); + .GetTypeInfo().GetDeclaredMethod(nameof(RelationalQueryableExtensions.AsSplitQuery))!; public override async Task Include_closes_reader(bool async) { diff --git a/test/EFCore.Relational.Specification.Tests/Query/NorthwindSqlQueryTestBase.cs b/test/EFCore.Relational.Specification.Tests/Query/NorthwindSqlQueryTestBase.cs index d2236ebef3e..8ec8e926cd5 100644 --- a/test/EFCore.Relational.Specification.Tests/Query/NorthwindSqlQueryTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/Query/NorthwindSqlQueryTestBase.cs @@ -9,8 +9,6 @@ // ReSharper disable AccessToDisposedClosure namespace Microsoft.EntityFrameworkCore.Query; -#nullable disable - public abstract class NorthwindSqlQueryTestBase : IClassFixture where TFixture : NorthwindQueryRelationalFixture, new() { diff --git a/test/EFCore.Relational.Specification.Tests/Query/NorthwindWhereQueryRelationalTestBase.cs b/test/EFCore.Relational.Specification.Tests/Query/NorthwindWhereQueryRelationalTestBase.cs index 92f78af1be0..de7af78c11c 100644 --- a/test/EFCore.Relational.Specification.Tests/Query/NorthwindWhereQueryRelationalTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/Query/NorthwindWhereQueryRelationalTestBase.cs @@ -5,8 +5,6 @@ namespace Microsoft.EntityFrameworkCore.Query; -#nullable disable - public abstract class NorthwindWhereQueryRelationalTestBase(TFixture fixture) : NorthwindWhereQueryTestBase(fixture) where TFixture : NorthwindQueryFixtureBase, new() { diff --git a/test/EFCore.Relational.Specification.Tests/Query/NullSemanticsQueryFixtureBase.cs b/test/EFCore.Relational.Specification.Tests/Query/NullSemanticsQueryFixtureBase.cs index 2c049055379..94a0cd450d7 100644 --- a/test/EFCore.Relational.Specification.Tests/Query/NullSemanticsQueryFixtureBase.cs +++ b/test/EFCore.Relational.Specification.Tests/Query/NullSemanticsQueryFixtureBase.cs @@ -6,20 +6,18 @@ namespace Microsoft.EntityFrameworkCore.Query; -#nullable disable - public abstract class NullSemanticsQueryFixtureBase : QueryFixtureBase, ITestSqlLoggerFactory { public override ISetSource GetExpectedData() => NullSemanticsData.Instance; - public override IReadOnlyDictionary EntitySorters { get; } = new Dictionary> + public override IReadOnlyDictionary EntitySorters { get; } = new Dictionary> { { typeof(NullSemanticsEntity1), e => ((NullSemanticsEntity1)e)?.Id }, { typeof(NullSemanticsEntity2), e => ((NullSemanticsEntity2)e)?.Id } }.ToDictionary(e => e.Key, e => (object)e.Value); - public override IReadOnlyDictionary EntityAsserters { get; } = new Dictionary> + public override IReadOnlyDictionary EntityAsserters { get; } = new Dictionary> { { typeof(NullSemanticsEntity1), (e, a) => @@ -27,7 +25,7 @@ public override ISetSource GetExpectedData() Assert.Equal(e == null, a == null); if (a != null) { - var ee = (NullSemanticsEntity1)e; + var ee = (NullSemanticsEntity1)e!; var aa = (NullSemanticsEntity1)a; Assert.Equal(ee.Id, aa.Id); @@ -58,7 +56,7 @@ public override ISetSource GetExpectedData() Assert.Equal(e == null, a == null); if (a != null) { - var ee = (NullSemanticsEntity2)e; + var ee = (NullSemanticsEntity2)e!; var aa = (NullSemanticsEntity2)a; Assert.Equal(ee.Id, aa.Id); diff --git a/test/EFCore.Relational.Specification.Tests/Query/NullSemanticsQueryTestBase.cs b/test/EFCore.Relational.Specification.Tests/Query/NullSemanticsQueryTestBase.cs index 2c23ef36f06..2dca76fc835 100644 --- a/test/EFCore.Relational.Specification.Tests/Query/NullSemanticsQueryTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/Query/NullSemanticsQueryTestBase.cs @@ -18,8 +18,6 @@ namespace Microsoft.EntityFrameworkCore.Query; -#nullable disable - public abstract class NullSemanticsQueryTestBase(TFixture fixture) : QueryTestBase(fixture) where TFixture : NullSemanticsQueryFixtureBase, new() { @@ -512,7 +510,7 @@ await AssertQueryScalar( [Theory, MemberData(nameof(IsAsyncData))] public virtual Task Compare_nullable_with_null_parameter_equal(bool async) { - string prm = null; + string? prm = null; return AssertQueryScalar(async, ss => ss.Set().Where(e => e.NullableStringA == prm).Select(e => e.Id)); } @@ -559,7 +557,7 @@ join e2 in ss.Set() on [Theory, MemberData(nameof(IsAsyncData))] public virtual Task Contains_with_local_array_closure_with_null(bool async) { - string[] ids = ["Foo", null]; + string?[] ids = ["Foo", null]; return AssertQueryScalar( async, ss => ss.Set().Where(e => ids.Contains(e.NullableStringA)).Select(e => e.Id)); @@ -568,7 +566,7 @@ public virtual Task Contains_with_local_array_closure_with_null(bool async) [Theory, MemberData(nameof(IsAsyncData))] public virtual Task Contains_with_local_array_closure_with_multiple_nulls(bool async) { - string[] ids = [null, "Foo", null, null]; + string?[] ids = [null, "Foo", null, null]; return AssertQueryScalar( async, ss => ss.Set().Where(e => ids.Contains(e.NullableStringA)).Select(e => e.Id)); @@ -577,7 +575,7 @@ public virtual Task Contains_with_local_array_closure_with_multiple_nulls(bool a [Theory, MemberData(nameof(IsAsyncData))] public virtual Task Contains_with_local_array_closure_false_with_null(bool async) { - string[] ids = ["Foo", null]; + string?[] ids = ["Foo", null]; return AssertQueryScalar( async, ss => ss.Set().Where(e => !ids.Contains(e.NullableStringA)).Select(e => e.Id)); @@ -609,7 +607,7 @@ public virtual Task Where_multiple_ands_with_null(bool async) [Theory, MemberData(nameof(IsAsyncData))] public virtual Task Where_multiple_ors_with_nullable_parameter(bool async) { - string prm = null; + string? prm = null; return AssertQueryScalar( async, @@ -619,8 +617,8 @@ public virtual Task Where_multiple_ors_with_nullable_parameter(bool async) [Theory, MemberData(nameof(IsAsyncData))] public virtual Task Where_multiple_ands_with_nullable_parameter_and_constant(bool async) { - string prm1 = null; - string prm2 = null; + string? prm1 = null; + string? prm2 = null; var prm3 = "Blah"; return AssertQueryScalar( @@ -634,8 +632,8 @@ public virtual Task Where_multiple_ands_with_nullable_parameter_and_constant(boo [Theory, MemberData(nameof(IsAsyncData))] public virtual Task Where_multiple_ands_with_nullable_parameter_and_constant_not_optimized(bool async) { - string prm1 = null; - string prm2 = null; + string? prm1 = null; + string? prm2 = null; var prm3 = "Blah"; return AssertQueryScalar( @@ -667,7 +665,7 @@ public virtual Task Where_coalesce_shortcircuit_many(bool async) [Theory, MemberData(nameof(IsAsyncData))] public virtual Task Where_equal_nullable_with_null_value_parameter(bool async) { - string prm = null; + string? prm = null; return AssertQueryScalar(async, ss => ss.Set().Where(e => e.NullableStringA == prm).Select(e => e.Id)); } @@ -675,7 +673,7 @@ public virtual Task Where_equal_nullable_with_null_value_parameter(bool async) [Theory, MemberData(nameof(IsAsyncData))] public virtual Task Where_not_equal_nullable_with_null_value_parameter(bool async) { - string prm = null; + string? prm = null; return AssertQueryScalar(async, ss => ss.Set().Where(e => e.NullableStringA != prm).Select(e => e.Id)); } @@ -768,7 +766,7 @@ public virtual Task Where_nested_conditional_search_condition_in_result(bool asy public virtual Task Where_equal_with_and_and_contains(bool async) => AssertQueryScalar( async, - ss => ss.Set().Where(e => e.NullableStringA.Contains(e.NullableStringB) && e.BoolA).Select(e => e.Id), + ss => ss.Set().Where(e => e.NullableStringA!.Contains(e.NullableStringB!) && e.BoolA).Select(e => e.Id), ss => ss.Set() .Where(e => e.NullableStringA != null && e.NullableStringA.Contains(e.NullableStringB ?? "Blah") && e.BoolA) .Select(e => e.Id)); @@ -834,7 +832,7 @@ public virtual void Where_contains_on_parameter_empty_array_with_relational_null public virtual void Where_contains_on_parameter_array_with_just_null_with_relational_null_semantics() { using var context = CreateContext(useRelationalNulls: true); - var names = new string[] { null }; + var names = new string?[] { null }; var result = context.Entities1 .Where(e => names.Contains(e.NullableStringA)) .Select(e => e.NullableStringA).ToList().Count; @@ -846,7 +844,7 @@ public virtual void Where_contains_on_parameter_array_with_just_null_with_relati public virtual Task Where_nullable_bool(bool async) => AssertQueryScalar( async, - ss => ss.Set().Where(e => e.NullableBoolA.Value).Select(e => e.Id), + ss => ss.Set().Where(e => e.NullableBoolA!.Value).Select(e => e.Id), ss => ss.Set().Where(e => e.NullableBoolA == true).Select(e => e.Id)); [Theory, MemberData(nameof(IsAsyncData))] @@ -924,7 +922,7 @@ public virtual void Where_not_equal_using_relational_null_semantics_complex_in_e [Theory, MemberData(nameof(IsAsyncData))] public virtual async Task Where_comparison_null_constant_and_null_parameter(bool async) { - string prm = null; + string? prm = null; await AssertQueryScalar(async, ss => ss.Set().Where(e => prm == null).Select(e => e.Id)); await AssertQueryScalar(async, ss => ss.Set().Where(e => prm != null).Select(e => e.Id), assertEmpty: true); @@ -942,7 +940,7 @@ public virtual async Task Where_comparison_null_constant_and_nonnull_parameter(b [Theory, MemberData(nameof(IsAsyncData))] public virtual async Task Where_comparison_nonnull_constant_and_null_parameter(bool async) { - string prm = null; + string? prm = null; await AssertQueryScalar(async, ss => ss.Set().Where(e => "Foo" == prm).Select(e => e.Id), assertEmpty: true); await AssertQueryScalar(async, ss => ss.Set().Where(e => "Foo" != prm).Select(e => e.Id)); @@ -951,7 +949,7 @@ public virtual async Task Where_comparison_nonnull_constant_and_null_parameter(b [Theory, MemberData(nameof(IsAsyncData))] public virtual Task Where_comparison_null_semantics_optimization_works_with_complex_predicates(bool async) { - string prm = null; + string? prm = null; return AssertQueryScalar( async, ss => ss.Set().Where(e => null == prm && e.NullableStringA == prm).Select(e => e.Id)); @@ -1053,19 +1051,19 @@ public virtual async Task Null_semantics_applied_when_comparing_function_with_nu { await AssertQueryScalar( async, - ss => ss.Set().Where(e => e.NullableStringA.IndexOf("oo") == e.NullableIntA).Select(e => e.Id), + ss => ss.Set().Where(e => e.NullableStringA!.IndexOf("oo") == e.NullableIntA).Select(e => e.Id), ss => ss.Set().Where(e => (e.NullableStringA == null && e.NullableIntA == null) || (e.NullableStringA != null && e.NullableStringA.IndexOf("oo") == e.NullableIntA)).Select(e => e.Id)); await AssertQueryScalar( async, - ss => ss.Set().Where(e => e.NullableStringA.IndexOf("ar") == e.NullableIntA).Select(e => e.Id), + ss => ss.Set().Where(e => e.NullableStringA!.IndexOf("ar") == e.NullableIntA).Select(e => e.Id), ss => ss.Set().Where(e => (e.NullableStringA == null && e.NullableIntA == null) || (e.NullableStringA != null && e.NullableStringA.IndexOf("ar") == e.NullableIntA)).Select(e => e.Id)); await AssertQueryScalar( async, - ss => ss.Set().Where(e => e.NullableStringA.IndexOf("oo") != e.NullableIntB).Select(e => e.Id), + ss => ss.Set().Where(e => e.NullableStringA!.IndexOf("oo") != e.NullableIntB).Select(e => e.Id), ss => ss.Set().Where(e => (e.NullableStringA == null && e.NullableIntB != null) || (e.NullableStringA != null && e.NullableStringA.IndexOf("oo") != e.NullableIntB)).Select(e => e.Id)); } @@ -1074,7 +1072,7 @@ await AssertQueryScalar( public virtual Task Where_IndexOf_empty(bool async) => AssertQueryScalar( async, - ss => ss.Set().Where(e => e.NullableStringA.IndexOf("") == e.NullableIntA).Select(e => e.Id), + ss => ss.Set().Where(e => e.NullableStringA!.IndexOf("") == e.NullableIntA).Select(e => e.Id), ss => ss.Set().Where(e => 0 == e.NullableIntA || (e.NullableStringA == null && e.NullableIntA == null)) .Select(e => e.Id)); @@ -1082,8 +1080,8 @@ public virtual Task Where_IndexOf_empty(bool async) public virtual Task Select_IndexOf(bool async) => AssertQueryScalar( async, - ss => ss.Set().OrderBy(e => e.Id).Select(e => (int?)e.NullableStringA.IndexOf("oo")), - ss => ss.Set().OrderBy(e => e.Id).Select(e => e.NullableStringA.MaybeScalar(x => x.IndexOf("oo"))), + ss => ss.Set().OrderBy(e => e.Id).Select(e => (int?)e.NullableStringA!.IndexOf("oo")), + ss => ss.Set().OrderBy(e => e.Id).Select(e => e.NullableStringA.MaybeScalar(x => x!.IndexOf("oo"))), assertOrder: true); [Theory, MemberData(nameof(IsAsyncData))] @@ -1091,24 +1089,24 @@ public virtual async Task Null_semantics_applied_when_comparing_two_functions_wi { await AssertQueryScalar( async, - ss => ss.Set().Where(e => e.NullableStringA.IndexOf("oo") == e.NullableStringB.IndexOf("ar")) + ss => ss.Set().Where(e => e.NullableStringA!.IndexOf("oo") == e.NullableStringB!.IndexOf("ar")) .Select(e => e.Id), - ss => ss.Set().Where(e => e.NullableStringA.MaybeScalar(x => x.IndexOf("oo")) - == e.NullableStringB.MaybeScalar(x => x.IndexOf("ar"))).Select(e => e.Id)); + ss => ss.Set().Where(e => e.NullableStringA.MaybeScalar(x => x!.IndexOf("oo")) + == e.NullableStringB.MaybeScalar(x => x!.IndexOf("ar"))).Select(e => e.Id)); await AssertQueryScalar( async, - ss => ss.Set().Where(e => e.NullableStringA.IndexOf("oo") != e.NullableStringB.IndexOf("ar")) + ss => ss.Set().Where(e => e.NullableStringA!.IndexOf("oo") != e.NullableStringB!.IndexOf("ar")) .Select(e => e.Id), - ss => ss.Set().Where(e => e.NullableStringA.MaybeScalar(x => x.IndexOf("oo")) - != e.NullableStringB.MaybeScalar(x => x.IndexOf("ar"))).Select(e => e.Id)); + ss => ss.Set().Where(e => e.NullableStringA.MaybeScalar(x => x!.IndexOf("oo")) + != e.NullableStringB.MaybeScalar(x => x!.IndexOf("ar"))).Select(e => e.Id)); await AssertQueryScalar( async, - ss => ss.Set().Where(e => e.NullableStringA.IndexOf("oo") != e.NullableStringA.IndexOf("ar")) + ss => ss.Set().Where(e => e.NullableStringA!.IndexOf("oo") != e.NullableStringA!.IndexOf("ar")) .Select(e => e.Id), - ss => ss.Set().Where(e => e.NullableStringA.MaybeScalar(x => x.IndexOf("oo")) - != e.NullableStringA.MaybeScalar(x => x.IndexOf("ar"))).Select(e => e.Id)); + ss => ss.Set().Where(e => e.NullableStringA.MaybeScalar(x => x!.IndexOf("oo")) + != e.NullableStringA.MaybeScalar(x => x!.IndexOf("ar"))).Select(e => e.Id)); } [Theory, MemberData(nameof(IsAsyncData))] @@ -1117,7 +1115,7 @@ public virtual async Task Null_semantics_applied_when_comparing_two_functions_wi await AssertQueryScalar( async, ss => ss.Set() - .Where(e => e.NullableStringA.Replace(e.NullableStringB, e.NullableStringC) == e.NullableStringA).Select(e => e.Id), + .Where(e => e.NullableStringA!.Replace(e.NullableStringB!, e.NullableStringC) == e.NullableStringA).Select(e => e.Id), ss => ss.Set().Where(e => (e.NullableStringA == null && (e.NullableStringA == null || e.NullableStringB == null || e.NullableStringC == null)) || (e.NullableStringA != null @@ -1128,7 +1126,7 @@ await AssertQueryScalar( await AssertQueryScalar( async, ss => ss.Set() - .Where(e => e.NullableStringA.Replace(e.NullableStringB, e.NullableStringC) != e.NullableStringA).Select(e => e.Id), + .Where(e => e.NullableStringA!.Replace(e.NullableStringB!, e.NullableStringC) != e.NullableStringA).Select(e => e.Id), ss => ss.Set().Where(e => ((e.NullableStringA == null || e.NullableStringB == null || e.NullableStringC == null) && e.NullableStringA != null) || (e.NullableStringA != null @@ -1182,9 +1180,9 @@ await AssertQueryScalar( public virtual Task Null_semantics_function(bool async) => AssertQueryScalar( async, - ss => ss.Set().Where(e => e.NullableStringA.Substring(0, e.IntA) != e.NullableStringB) + ss => ss.Set().Where(e => e.NullableStringA!.Substring(0, e.IntA) != e.NullableStringB) .Select(e => e.Id), - ss => ss.Set().Where(e => e.NullableStringA.Maybe(x => x.Substring(0, e.IntA)) != e.NullableStringB) + ss => ss.Set().Where(e => e.NullableStringA.Maybe(x => x!.Substring(0, e.IntA)) != e.NullableStringB) .Select(e => e.Id)); [Theory, MemberData(nameof(IsAsyncData))] @@ -1726,7 +1724,7 @@ public virtual async Task String_concat_with_both_arguments_being_null(bool asyn await AssertQuery(async, ss => ss.Set().Select(x => prm + x.NullableStringA)); await AssertQuery(async, ss => ss.Set().Select(x => null + prm)); - await AssertQuery(async, ss => ss.Set().Select(x => (string)null + null)); + await AssertQuery(async, ss => ss.Set().Select(x => (string)null! + null)); await AssertQuery(async, ss => ss.Set().Select(x => null + x.NullableStringA)); await AssertQuery(async, ss => ss.Set().Select(x => x.NullableStringB + prm)); @@ -1753,31 +1751,31 @@ public virtual Task Empty_subquery_with_contains_negated_returns_true(bool async public virtual Task Nullable_string_FirstOrDefault_compared_to_nullable_string_LastOrDefault(bool async) => AssertQuery( async, - ss => ss.Set().Where(e => e.NullableStringA.FirstOrDefault() == e.NullableStringB.LastOrDefault()), - ss => ss.Set().Where(e => e.NullableStringA.MaybeScalar(x => x.FirstOrDefault()) - == e.NullableStringB.MaybeScalar(x => x.LastOrDefault()))); + ss => ss.Set().Where(e => e.NullableStringA!.FirstOrDefault() == e.NullableStringB!.LastOrDefault()), + ss => ss.Set().Where(e => e.NullableStringA.MaybeScalar(x => x!.FirstOrDefault()) + == e.NullableStringB.MaybeScalar(x => x!.LastOrDefault()))); [Theory, MemberData(nameof(IsAsyncData))] public virtual async Task Null_semantics_applied_to_CompareTo_equality(bool async) { await AssertQuery( async, - ss => ss.Set().Where(e => e.NullableStringA.CompareTo(e.NullableStringB) == 0), + ss => ss.Set().Where(e => e.NullableStringA!.CompareTo(e.NullableStringB) == 0), ss => ss.Set().Where(e => e.NullableStringA == e.NullableStringB)); await AssertQuery( async, - ss => ss.Set().Where(e => 0 == e.NullableStringA.CompareTo(e.NullableStringB)), + ss => ss.Set().Where(e => 0 == e.NullableStringA!.CompareTo(e.NullableStringB)), ss => ss.Set().Where(e => e.NullableStringA == e.NullableStringB)); await AssertQuery( async, - ss => ss.Set().Where(e => e.NullableStringA.CompareTo(e.NullableStringB) != 0), + ss => ss.Set().Where(e => e.NullableStringA!.CompareTo(e.NullableStringB) != 0), ss => ss.Set().Where(e => e.NullableStringA != e.NullableStringB)); await AssertQuery( async, - ss => ss.Set().Where(e => 0 != e.NullableStringA.CompareTo(e.NullableStringB)), + ss => ss.Set().Where(e => 0 != e.NullableStringA!.CompareTo(e.NullableStringB)), ss => ss.Set().Where(e => e.NullableStringA != e.NullableStringB)); } @@ -1786,22 +1784,22 @@ public virtual async Task Nested_CompareTo_optimized(bool async) { await AssertQuery( async, - ss => ss.Set().Where(e => e.NullableStringA.CompareTo(e.NullableStringB).CompareTo(0) == 0), + ss => ss.Set().Where(e => e.NullableStringA!.CompareTo(e.NullableStringB).CompareTo(0) == 0), ss => ss.Set().Where(e => e.NullableStringA == e.NullableStringB)); await AssertQuery( async, - ss => ss.Set().Where(e => 0 == e.NullableStringA.CompareTo(e.NullableStringB).CompareTo(0)), + ss => ss.Set().Where(e => 0 == e.NullableStringA!.CompareTo(e.NullableStringB).CompareTo(0)), ss => ss.Set().Where(e => e.NullableStringA == e.NullableStringB)); await AssertQuery( async, - ss => ss.Set().Where(e => e.NullableStringA.CompareTo(e.NullableStringB).CompareTo(0) != 0), + ss => ss.Set().Where(e => e.NullableStringA!.CompareTo(e.NullableStringB).CompareTo(0) != 0), ss => ss.Set().Where(e => e.NullableStringA != e.NullableStringB)); await AssertQuery( async, - ss => ss.Set().Where(e => 0 != e.NullableStringA.CompareTo(e.NullableStringB).CompareTo(0)), + ss => ss.Set().Where(e => 0 != e.NullableStringA!.CompareTo(e.NullableStringB).CompareTo(0)), ss => ss.Set().Where(e => e.NullableStringA != e.NullableStringB)); } @@ -2349,7 +2347,7 @@ await AssertQueryScalar( // We can't client-evaluate Like (for the expected results). // However, since the test data has no LIKE wildcards, it effectively functions like equality - except that 'null like null' returns // false instead of true. So we have this "lite" implementation which doesn't support wildcards. - private bool LikeLite(string s, string pattern) + private bool LikeLite(string? s, string? pattern) => s == pattern && s is not null && pattern is not null; private string NormalizeDelimitersInRawString(string sql) diff --git a/test/EFCore.Relational.Specification.Tests/Query/OperatorsProceduralQueryTestBase.cs b/test/EFCore.Relational.Specification.Tests/Query/OperatorsProceduralQueryTestBase.cs index 4009de032f6..e04c7e4a15d 100644 --- a/test/EFCore.Relational.Specification.Tests/Query/OperatorsProceduralQueryTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/Query/OperatorsProceduralQueryTestBase.cs @@ -5,17 +5,15 @@ namespace Microsoft.EntityFrameworkCore.Query; -#nullable disable - public abstract class OperatorsProceduralQueryTestBase : NonSharedModelTestBase, IClassFixture { private static readonly MethodInfo LikeMethodInfo = typeof(DbFunctionsExtensions).GetRuntimeMethod( - nameof(DbFunctionsExtensions.Like), [typeof(DbFunctions), typeof(string), typeof(string)]); + nameof(DbFunctionsExtensions.Like), [typeof(DbFunctions), typeof(string), typeof(string)])!; private static readonly MethodInfo StringConcatMethodInfo = typeof(string).GetRuntimeMethod( - nameof(string.Concat), [typeof(string), typeof(string)]); + nameof(string.Concat), [typeof(string), typeof(string)])!; protected readonly List<((Type Left, Type Right) InputTypes, Type ResultType, Func OperatorCreator)> Binaries; @@ -243,7 +241,7 @@ private Expression GenerateTestExpression( Type[] types, RootEntityExpressionInfo[] rootEntityExpressions, int maxDepth, - Type startingResultType) + Type? startingResultType) { var distinctTypes = types.Distinct().ToList(); var possibleLeafBinaries = @@ -470,7 +468,7 @@ private void TestProjectionQuery( BindingFlags.NonPublic | BindingFlags.Instance); var genericArguments = roots.Select(x => PropertyTypeToEntityMap[x.Type]).Concat([resultExpression.Type]).ToArray(); - var genericMethod = method.MakeGenericMethod(genericArguments); + var genericMethod = method!.MakeGenericMethod(genericArguments); var resultRewriter = new ResultExpressionProjectionRewriter(resultExpression, roots); @@ -488,7 +486,7 @@ private void TestProjectionQueryWithOneSource( var setSourceTemplate = (ISetSource ss) => from e1 in ss.Set() orderby e1.Id - select new OperatorDto1(e1, default); + select new OperatorDto1(e1, default!); ExecuteQueryAndVerifyResults( seed, @@ -513,7 +511,7 @@ private void TestProjectionQueryWithTwoSources( from e1 in ss.Set() from e2 in ss.Set() orderby e1.Id, e2.Id - select new OperatorDto2(e1, e2, default); + select new OperatorDto2(e1, e2, default!); ExecuteQueryAndVerifyResults( seed, @@ -541,7 +539,7 @@ from e1 in ss.Set() from e2 in ss.Set() from e3 in ss.Set() orderby e1.Id, e2.Id, e3.Id - select new OperatorDto3(e1, e2, e3, default); + select new OperatorDto3(e1, e2, e3, default!); ExecuteQueryAndVerifyResults( seed, @@ -572,7 +570,7 @@ from e2 in ss.Set() from e3 in ss.Set() from e4 in ss.Set() orderby e1.Id, e2.Id, e3.Id, e4.Id - select new OperatorDto4(e1, e2, e3, e4, default); + select new OperatorDto4(e1, e2, e3, e4, default!); ExecuteQueryAndVerifyResults( seed, @@ -606,7 +604,7 @@ from e3 in ss.Set() from e4 in ss.Set() from e5 in ss.Set() orderby e1.Id, e2.Id, e3.Id, e4.Id, e5.Id - select new OperatorDto5(e1, e2, e3, e4, e5, default); + select new OperatorDto5(e1, e2, e3, e4, e5, default!); ExecuteQueryAndVerifyResults( seed, @@ -643,7 +641,7 @@ from e4 in ss.Set() from e5 in ss.Set() from e6 in ss.Set() orderby e1.Id, e2.Id, e3.Id, e4.Id, e5.Id, e6.Id - select new OperatorDto6(e1, e2, e3, e4, e5, e6, default); + select new OperatorDto6(e1, e2, e3, e4, e5, e6, default!); ExecuteQueryAndVerifyResults( seed, @@ -932,7 +930,7 @@ private void TestPredicateQuery( methodName, BindingFlags.NonPublic | BindingFlags.Instance); - var genericMethod = method.MakeGenericMethod(roots.Select(x => PropertyTypeToEntityMap[x.Type]).ToArray()); + var genericMethod = method!.MakeGenericMethod(roots.Select(x => PropertyTypeToEntityMap[x.Type]).ToArray()); var resultRewriter = new ResultExpressionPredicateRewriter(resultExpression, roots); @@ -1163,7 +1161,7 @@ private class ResultExpressionPredicateRewriter(Expression resultExpression, Exp { private static readonly MethodInfo _likeMethodInfo = typeof(DbFunctionsExtensions).GetRuntimeMethod( - nameof(DbFunctionsExtensions.Like), [typeof(DbFunctions), typeof(string), typeof(string)]); + nameof(DbFunctionsExtensions.Like), [typeof(DbFunctions), typeof(string), typeof(string)])!; private readonly Expression[] _roots = roots; private readonly Expression _resultExpression = resultExpression; diff --git a/test/EFCore.Relational.Specification.Tests/Query/OperatorsQueryTestBase.cs b/test/EFCore.Relational.Specification.Tests/Query/OperatorsQueryTestBase.cs index 3f973a9e7d3..03835508f2c 100644 --- a/test/EFCore.Relational.Specification.Tests/Query/OperatorsQueryTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/Query/OperatorsQueryTestBase.cs @@ -297,11 +297,11 @@ public virtual async Task Negate_on_like_expression(bool async) using var context = contextFactory.CreateDbContext(); var expected = (from e in ExpectedData.OperatorEntitiesString - where !e.Value.StartsWith("A") + where !e.Value!.StartsWith("A") select e.Id).ToList(); var actual = (from e in context.Set() - where !e.Value.StartsWith("A") + where !e.Value!.StartsWith("A") select e.Id).ToList(); Assert.Equal(expected.Count, actual.Count); diff --git a/test/EFCore.Relational.Specification.Tests/Query/OptionalDependentQueryFixtureBase.cs b/test/EFCore.Relational.Specification.Tests/Query/OptionalDependentQueryFixtureBase.cs index a20ff05b4dd..c521b579952 100644 --- a/test/EFCore.Relational.Specification.Tests/Query/OptionalDependentQueryFixtureBase.cs +++ b/test/EFCore.Relational.Specification.Tests/Query/OptionalDependentQueryFixtureBase.cs @@ -5,23 +5,21 @@ namespace Microsoft.EntityFrameworkCore.Query; -#nullable disable - public abstract class OptionalDependentQueryFixtureBase : QueryFixtureBase, ITestSqlLoggerFactory { - private OptionalDependentData _expectedData; + private OptionalDependentData? _expectedData; public override ISetSource GetExpectedData() => _expectedData ??= new OptionalDependentData(); - public override IReadOnlyDictionary EntitySorters { get; } = new Dictionary> + public override IReadOnlyDictionary EntitySorters { get; } = new Dictionary> { { typeof(OptionalDependentEntityAllOptional), e => ((OptionalDependentEntityAllOptional)e)?.Id }, { typeof(OptionalDependentEntitySomeRequired), e => ((OptionalDependentEntitySomeRequired)e)?.Id }, }.ToDictionary(e => e.Key, e => (object)e.Value); - public override IReadOnlyDictionary EntityAsserters { get; } = new Dictionary> + public override IReadOnlyDictionary EntityAsserters { get; } = new Dictionary> { { typeof(OptionalDependentEntityAllOptional), (e, a) => @@ -29,7 +27,7 @@ public override ISetSource GetExpectedData() Assert.Equal(e == null, a == null); if (a != null) { - var ee = (OptionalDependentEntityAllOptional)e; + var ee = (OptionalDependentEntityAllOptional)e!; var aa = (OptionalDependentEntityAllOptional)a; Assert.Equal(ee.Id, aa.Id); @@ -37,7 +35,7 @@ public override ISetSource GetExpectedData() if (ee.Json is not null || aa.Json is not null) { - AssertOptionalDependentJsonAllOptional(ee.Json, aa.Json); + AssertOptionalDependentJsonAllOptional(ee.Json!, aa.Json!); } } } @@ -48,7 +46,7 @@ public override ISetSource GetExpectedData() Assert.Equal(e == null, a == null); if (a != null) { - var ee = (OptionalDependentEntitySomeRequired)e; + var ee = (OptionalDependentEntitySomeRequired)e!; var aa = (OptionalDependentEntitySomeRequired)a; Assert.Equal(ee.Id, aa.Id); @@ -56,7 +54,7 @@ public override ISetSource GetExpectedData() if (ee.Json is not null || aa.Json is not null) { - AssertOptionalDependentJsonSomeRequired(ee.Json, aa.Json); + AssertOptionalDependentJsonSomeRequired(ee.Json!, aa.Json!); } } } @@ -72,12 +70,12 @@ public static void AssertOptionalDependentJsonAllOptional( if (expected.OpNav1 is not null || actual.OpNav1 is not null) { - AssertOptionalDependentNestedJsonAllOptional(expected.OpNav1, actual.OpNav1); + AssertOptionalDependentNestedJsonAllOptional(expected.OpNav1!, actual.OpNav1!); } if (expected.OpNav2 is not null || actual.OpNav2 is not null) { - AssertOptionalDependentNestedJsonSomeRequired(expected.OpNav2, actual.OpNav2); + AssertOptionalDependentNestedJsonSomeRequired(expected.OpNav2!, actual.OpNav2!); } } @@ -91,12 +89,12 @@ public static void AssertOptionalDependentJsonSomeRequired( if (expected.OpNav1 is not null || actual.OpNav1 is not null) { - AssertOptionalDependentNestedJsonAllOptional(expected.OpNav1, actual.OpNav1); + AssertOptionalDependentNestedJsonAllOptional(expected.OpNav1!, actual.OpNav1!); } if (expected.OpNav2 is not null || actual.OpNav2 is not null) { - AssertOptionalDependentNestedJsonSomeRequired(expected.OpNav2, actual.OpNav2); + AssertOptionalDependentNestedJsonSomeRequired(expected.OpNav2!, actual.OpNav2!); } AssertOptionalDependentNestedJsonAllOptional(expected.ReqNav1, actual.ReqNav1); diff --git a/test/EFCore.Relational.Specification.Tests/Query/OptionalDependentQueryTestBase.cs b/test/EFCore.Relational.Specification.Tests/Query/OptionalDependentQueryTestBase.cs index 09a04d14b43..f14852c78ad 100644 --- a/test/EFCore.Relational.Specification.Tests/Query/OptionalDependentQueryTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/Query/OptionalDependentQueryTestBase.cs @@ -5,8 +5,6 @@ namespace Microsoft.EntityFrameworkCore.Query; -#nullable disable - public abstract class OptionalDependentQueryTestBase(TFixture fixture) : QueryTestBase(fixture) where TFixture : OptionalDependentQueryFixtureBase, new() { @@ -50,23 +48,23 @@ public virtual Task Filter_optional_dependent_with_some_required_compared_to_not public virtual Task Filter_nested_optional_dependent_with_all_optional_compared_to_null(bool async) => AssertQuery( async, - ss => ss.Set().Where(x => x.Json.OpNav1 == null)); + ss => ss.Set().Where(x => x.Json!.OpNav1 == null)); [Theory, MemberData(nameof(IsAsyncData))] public virtual Task Filter_nested_optional_dependent_with_all_optional_compared_to_not_null(bool async) => AssertQuery( async, - ss => ss.Set().Where(x => x.Json.OpNav2 != null)); + ss => ss.Set().Where(x => x.Json!.OpNav2 != null)); [Theory, MemberData(nameof(IsAsyncData))] public virtual Task Filter_nested_optional_dependent_with_some_required_compared_to_null(bool async) => AssertQuery( async, - ss => ss.Set().Where(x => x.Json.ReqNav1 == null)); + ss => ss.Set().Where(x => x.Json!.ReqNav1 == null)); [Theory, MemberData(nameof(IsAsyncData))] public virtual Task Filter_nested_optional_dependent_with_some_required_compared_to_not_null(bool async) => AssertQuery( async, - ss => ss.Set().Where(x => x.Json.ReqNav2 != null)); + ss => ss.Set().Where(x => x.Json!.ReqNav2 != null)); } diff --git a/test/EFCore.Relational.Specification.Tests/Query/OwnedEntityQueryRelationalTestBase.cs b/test/EFCore.Relational.Specification.Tests/Query/OwnedEntityQueryRelationalTestBase.cs index bde826777b3..c7d55545216 100644 --- a/test/EFCore.Relational.Specification.Tests/Query/OwnedEntityQueryRelationalTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/Query/OwnedEntityQueryRelationalTestBase.cs @@ -3,8 +3,6 @@ namespace Microsoft.EntityFrameworkCore.Query; -#nullable disable - public abstract class OwnedEntityQueryRelationalTestBase(NonSharedFixture fixture) : OwnedEntityQueryTestBase(fixture) { protected TestSqlLoggerFactory TestSqlLoggerFactory @@ -42,24 +40,24 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) public class AnAggregateRoot { - public string Id { get; set; } - public AnOwnedTypeWithOwnedProperties AnOwnedTypeWithOwnedProperties { get; set; } + public string Id { get; set; } = null!; + public AnOwnedTypeWithOwnedProperties? AnOwnedTypeWithOwnedProperties { get; set; } } public class AnOwnedTypeWithOwnedProperties { - public AnOwnedTypeWithPrimitiveProperties1 AnOwnedTypeWithPrimitiveProperties1 { get; set; } - public AnOwnedTypeWithPrimitiveProperties2 AnOwnedTypeWithPrimitiveProperties2 { get; set; } + public AnOwnedTypeWithPrimitiveProperties1? AnOwnedTypeWithPrimitiveProperties1 { get; set; } + public AnOwnedTypeWithPrimitiveProperties2? AnOwnedTypeWithPrimitiveProperties2 { get; set; } } public class AnOwnedTypeWithPrimitiveProperties1 { - public string Name { get; set; } + public string? Name { get; set; } } public class AnOwnedTypeWithPrimitiveProperties2 { - public string Name { get; set; } + public string? Name { get; set; } } } @@ -84,7 +82,7 @@ public virtual async Task Multiple_owned_reference_mapped_to_own_table_containin // Protected so that it can be used by inheriting tests, and so that things like unused setters are not removed. protected class Context24777(DbContextOptions options) : DbContext(options) { - public DbSet Roots { get; set; } + public DbSet Roots { get; set; } = null!; protected override void OnModelCreating(ModelBuilder modelBuilder) => modelBuilder.Entity(b => @@ -147,15 +145,15 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) public class Root { public int Id { get; init; } - public ModdleA ModdleA { get; init; } - public MiddleB MiddleB { get; init; } + public ModdleA ModdleA { get; init; } = null!; + public MiddleB? MiddleB { get; init; } } public class ModdleA { public int Id { get; init; } public int RootId { get; init; } - public List Leaves { get; } + public List Leaves { get; } = null!; } public class MiddleB @@ -210,18 +208,18 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) protected class Location25680 { public Guid Id { get; set; } - public ICollection PublishTokenTypes { get; set; } + public ICollection PublishTokenTypes { get; set; } = null!; } protected class PublishTokenType25680 { - public Location25680 Location { get; set; } + public Location25680 Location { get; set; } = null!; public Guid LocationId { get; set; } - public string ExternalId { get; set; } - public string VisualNumber { get; set; } - public string TokenGroupId { get; set; } - public string IssuerName { get; set; } + public string ExternalId { get; set; } = null!; + public string VisualNumber { get; set; } = null!; + public string TokenGroupId { get; set; } = null!; + public string IssuerName { get; set; } = null!; } #endregion @@ -317,7 +315,7 @@ public virtual async Task Owned_entity_with_all_null_properties_entity_equality_ result, t => { - Assert.Equal(1, t.ServiceType); + Assert.Equal(1, t!.ServiceType); Assert.Equal("1", t.ApartmentNo); }); } @@ -343,7 +341,7 @@ public virtual async Task Owned_entity_with_all_null_properties_in_compared_to_n result, t => { - Assert.Equal("1", t.MyApartmentNo); + Assert.Equal("1", t!.MyApartmentNo); Assert.Equal(1, t.MyServiceType); }, Assert.Null); @@ -370,7 +368,7 @@ public virtual async Task Owned_entity_with_all_null_properties_in_compared_to_n result, t => { - Assert.Equal("1", t.MyApartmentNo); + Assert.Equal("1", t!.MyApartmentNo); Assert.Equal(1, t.MyServiceType); }, Assert.Null); @@ -382,7 +380,7 @@ public virtual async Task Owned_entity_with_all_null_properties_property_access_ var contextFactory = await InitializeNonSharedTest(seed: c => c.SeedAsync()); using var context = contextFactory.CreateDbContext(); - var query = context.RotRutCases.AsNoTracking().Select(e => e.Rot.ApartmentNo); + var query = context.RotRutCases.AsNoTracking().Select(e => e.Rot!.ApartmentNo); var result = async ? await query.ToListAsync() @@ -397,7 +395,7 @@ public virtual async Task Owned_entity_with_all_null_properties_property_access_ // Protected so that it can be used by inheriting tests, and so that things like unused setters are not removed. protected class Context28247(DbContextOptions options) : DbContext(options) { - public DbSet RotRutCases { get; set; } + public DbSet RotRutCases { get; set; } = null!; protected override void OnModelCreating(ModelBuilder modelBuilder) => modelBuilder.Entity(b => @@ -432,21 +430,21 @@ public Task SeedAsync() public class RotRutCase { public int Id { get; set; } - public string Buyer { get; set; } - public Rot Rot { get; set; } - public Rut Rut { get; set; } + public string Buyer { get; set; } = null!; + public Rot? Rot { get; set; } + public Rut? Rut { get; set; } } public class Rot { public int? ServiceType { get; set; } - public string ApartmentNo { get; set; } + public string? ApartmentNo { get; set; } } public class RotDto { public int? MyServiceType { get; set; } - public string MyApartmentNo { get; set; } + public string? MyApartmentNo { get; set; } } public class Rut @@ -479,8 +477,8 @@ join magus in context.Magi.Where(x => x.Name.Contains("Bayaz")) on monarch.Ruler // Protected so that it can be used by inheriting tests, and so that things like unused setters are not removed. protected class Context30358(DbContextOptions options) : DbContext(options) { - public DbSet Monarchs { get; set; } - public DbSet Magi { get; set; } + public DbSet Monarchs { get; set; } = null!; + public DbSet Magi { get; set; } = null!; protected override void OnModelCreating(ModelBuilder modelBuilder) => modelBuilder.Entity().OwnsOne(x => x.ToolUsed, x => x.ToTable("MagicTools")); @@ -523,21 +521,21 @@ public Task SeedAsync() public class Monarch { public int Id { get; set; } - public string Name { get; set; } - public string RulerOf { get; set; } + public string Name { get; set; } = null!; + public string RulerOf { get; set; } = null!; } public class Magus { public int Id { get; set; } - public string Name { get; set; } - public string Affiliation { get; set; } - public MagicTool ToolUsed { get; set; } + public string Name { get; set; } = null!; + public string Affiliation { get; set; } = null!; + public MagicTool ToolUsed { get; set; } = null!; } public class MagicTool { - public string Name { get; set; } + public string Name { get; set; } = null!; } } @@ -592,7 +590,7 @@ public sealed class ChildData public sealed class Child1Entity : BaseEntity { - public ChildData Data { get; set; } + public ChildData Data { get; set; } = null!; } public sealed class Child2Entity : BaseEntity; @@ -655,7 +653,7 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) public class RootEntity { public Guid Id { get; set; } - public Outer Outer { get; set; } + public Outer? Outer { get; set; } } public class Outer diff --git a/test/EFCore.Relational.Specification.Tests/Query/OwnedQueryRelationalTestBase.cs b/test/EFCore.Relational.Specification.Tests/Query/OwnedQueryRelationalTestBase.cs index da0a2dc170c..04e95b68fb7 100644 --- a/test/EFCore.Relational.Specification.Tests/Query/OwnedQueryRelationalTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/Query/OwnedQueryRelationalTestBase.cs @@ -3,8 +3,6 @@ namespace Microsoft.EntityFrameworkCore.Query; -#nullable disable - public abstract class OwnedQueryRelationalTestBase(TFixture fixture) : OwnedQueryTestBase(fixture) where TFixture : OwnedQueryRelationalTestBase.RelationalOwnedQueryFixture, new() { @@ -60,7 +58,7 @@ public virtual Task Project_multiple_owned_navigations_split(bool async) { p.Orders, p.PersonAddress, - p.PersonAddress.Country.Planet + p.PersonAddress!.Country!.Planet }), assertOrder: true, elementAsserter: (e, a) => @@ -74,7 +72,7 @@ public virtual Task Project_multiple_owned_navigations_split(bool async) public virtual Task Navigation_rewrite_on_owned_reference_followed_by_regular_entity_and_collection_split(bool async) => AssertQuery( async, - ss => ss.Set().OrderBy(p => p.Id).Select(p => p.PersonAddress.Country.Planet.Moons).AsSplitQuery(), + ss => ss.Set().OrderBy(p => p.Id).Select(p => p.PersonAddress!.Country!.Planet!.Moons).AsSplitQuery(), assertOrder: true, elementAsserter: (e, a) => AssertCollection(e, a)); diff --git a/test/EFCore.Relational.Specification.Tests/Query/PrimitiveCollectionsQueryRelationalTestBase.cs b/test/EFCore.Relational.Specification.Tests/Query/PrimitiveCollectionsQueryRelationalTestBase.cs index 3c821e2787e..ecbd023f503 100644 --- a/test/EFCore.Relational.Specification.Tests/Query/PrimitiveCollectionsQueryRelationalTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/Query/PrimitiveCollectionsQueryRelationalTestBase.cs @@ -3,8 +3,6 @@ namespace Microsoft.EntityFrameworkCore.Query; -#nullable disable - public abstract class PrimitiveCollectionsQueryRelationalTestBase(TFixture fixture) : PrimitiveCollectionsQueryTestBase(fixture) where TFixture : PrimitiveCollectionsQueryTestBase.PrimitiveCollectionsQueryFixtureBase, new() diff --git a/test/EFCore.Relational.Specification.Tests/Query/QueryFilterFuncletizationRelationalFixture.cs b/test/EFCore.Relational.Specification.Tests/Query/QueryFilterFuncletizationRelationalFixture.cs index 10924bcaf6f..75c07462e89 100644 --- a/test/EFCore.Relational.Specification.Tests/Query/QueryFilterFuncletizationRelationalFixture.cs +++ b/test/EFCore.Relational.Specification.Tests/Query/QueryFilterFuncletizationRelationalFixture.cs @@ -3,8 +3,6 @@ namespace Microsoft.EntityFrameworkCore.Query; -#nullable disable - public abstract class QueryFilterFuncletizationRelationalFixture : QueryFilterFuncletizationFixtureBase, ITestSqlLoggerFactory { public TestSqlLoggerFactory TestSqlLoggerFactory diff --git a/test/EFCore.Relational.Specification.Tests/Query/QueryNoClientEvalTestBase.cs b/test/EFCore.Relational.Specification.Tests/Query/QueryNoClientEvalTestBase.cs index d9893c7320a..a8b0b751f6d 100644 --- a/test/EFCore.Relational.Specification.Tests/Query/QueryNoClientEvalTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/Query/QueryNoClientEvalTestBase.cs @@ -7,8 +7,6 @@ // ReSharper disable InconsistentNaming namespace Microsoft.EntityFrameworkCore.Query; -#nullable disable - public abstract class QueryNoClientEvalTestBase(TFixture fixture) : IClassFixture where TFixture : NorthwindQueryRelationalFixture, new() { diff --git a/test/EFCore.Relational.Specification.Tests/Query/RelationalNorthwindDbFunctionsQueryTestBase.cs b/test/EFCore.Relational.Specification.Tests/Query/RelationalNorthwindDbFunctionsQueryTestBase.cs index cad12880b47..aef47b1c62f 100644 --- a/test/EFCore.Relational.Specification.Tests/Query/RelationalNorthwindDbFunctionsQueryTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/Query/RelationalNorthwindDbFunctionsQueryTestBase.cs @@ -5,8 +5,6 @@ namespace Microsoft.EntityFrameworkCore.Query; -#nullable disable - public abstract class NorthwindDbFunctionsQueryRelationalTestBase(TFixture fixture) : NorthwindDbFunctionsQueryTestBase(fixture) where TFixture : NorthwindQueryRelationalFixture, new() @@ -18,7 +16,7 @@ public virtual Task Collate_case_insensitive(bool async) ss => ss.Set(), ss => ss.Set(), c => EF.Functions.Collate(c.ContactName, CaseInsensitiveCollation) == "maria anders", - c => c.ContactName.Equals("maria anders", StringComparison.OrdinalIgnoreCase)); + c => c.ContactName!.Equals("maria anders", StringComparison.OrdinalIgnoreCase)); [Theory, MemberData(nameof(IsAsyncData))] public virtual Task Collate_case_sensitive(bool async) @@ -27,7 +25,7 @@ public virtual Task Collate_case_sensitive(bool async) ss => ss.Set(), ss => ss.Set(), c => EF.Functions.Collate(c.ContactName, CaseSensitiveCollation) == "maria anders", - c => c.ContactName.Equals("maria anders", StringComparison.Ordinal)); + c => c.ContactName!.Equals("maria anders", StringComparison.Ordinal)); [Theory, MemberData(nameof(IsAsyncData))] public virtual Task Collate_case_sensitive_constant(bool async) @@ -36,7 +34,7 @@ public virtual Task Collate_case_sensitive_constant(bool async) ss => ss.Set(), ss => ss.Set(), c => c.ContactName == EF.Functions.Collate("maria anders", CaseSensitiveCollation), - c => c.ContactName.Equals("maria anders", StringComparison.Ordinal)); + c => c.ContactName!.Equals("maria anders", StringComparison.Ordinal)); [Theory, MemberData(nameof(IsAsyncData))] public virtual Task Collate_is_null(bool async) diff --git a/test/EFCore.Relational.Specification.Tests/Query/SharedTypeQueryRelationalTestBase.cs b/test/EFCore.Relational.Specification.Tests/Query/SharedTypeQueryRelationalTestBase.cs index 86adf68250e..45976af54ba 100644 --- a/test/EFCore.Relational.Specification.Tests/Query/SharedTypeQueryRelationalTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/Query/SharedTypeQueryRelationalTestBase.cs @@ -3,8 +3,6 @@ namespace Microsoft.EntityFrameworkCore.Query; -#nullable disable - public abstract class SharedTypeQueryRelationalTestBase(NonSharedFixture fixture) : SharedTypeQueryTestBase(fixture) { protected TestSqlLoggerFactory TestSqlLoggerFactory diff --git a/test/EFCore.Relational.Specification.Tests/Query/SpatialQueryRelationalFixture.cs b/test/EFCore.Relational.Specification.Tests/Query/SpatialQueryRelationalFixture.cs index 4ff338cc88f..94426631257 100644 --- a/test/EFCore.Relational.Specification.Tests/Query/SpatialQueryRelationalFixture.cs +++ b/test/EFCore.Relational.Specification.Tests/Query/SpatialQueryRelationalFixture.cs @@ -3,8 +3,6 @@ namespace Microsoft.EntityFrameworkCore.Query; -#nullable disable - public abstract class SpatialQueryRelationalFixture : SpatialQueryFixtureBase, ITestSqlLoggerFactory { public new RelationalTestStore TestStore diff --git a/test/EFCore.Relational.Specification.Tests/Query/SpatialQueryRelationalTestBase.cs b/test/EFCore.Relational.Specification.Tests/Query/SpatialQueryRelationalTestBase.cs index 9cb562a0370..44217037bb3 100644 --- a/test/EFCore.Relational.Specification.Tests/Query/SpatialQueryRelationalTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/Query/SpatialQueryRelationalTestBase.cs @@ -3,7 +3,5 @@ namespace Microsoft.EntityFrameworkCore.Query; -#nullable disable - public abstract class SpatialQueryRelationalTestBase(TFixture fixture) : SpatialQueryTestBase(fixture) where TFixture : SpatialQueryFixtureBase, new(); diff --git a/test/EFCore.Relational.Specification.Tests/Query/SqlExecutorTestBase.cs b/test/EFCore.Relational.Specification.Tests/Query/SqlExecutorTestBase.cs index b1f797b6771..bd1f9f79501 100644 --- a/test/EFCore.Relational.Specification.Tests/Query/SqlExecutorTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/Query/SqlExecutorTestBase.cs @@ -9,8 +9,6 @@ // ReSharper disable ConvertToConstant.Local namespace Microsoft.EntityFrameworkCore.Query; -#nullable disable - public abstract class SqlExecutorTestBase(TFixture fixture) : IClassFixture where TFixture : NorthwindQueryRelationalFixture, new() { @@ -142,7 +140,7 @@ public virtual async Task Query_with_positional_dbParameter_with_name(bool async [Theory, InlineData(false), InlineData(true)] public virtual async Task Query_with_positional_dbParameter_without_name(bool async) { - var city = CreateDbParameter(name: null, value: "London"); + var city = CreateDbParameter(name: null!, value: "London"); using var context = CreateContext(); diff --git a/test/EFCore.Relational.Specification.Tests/Query/SqlQueryTestBase.cs b/test/EFCore.Relational.Specification.Tests/Query/SqlQueryTestBase.cs index 113478d5567..e188fc529a9 100644 --- a/test/EFCore.Relational.Specification.Tests/Query/SqlQueryTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/Query/SqlQueryTestBase.cs @@ -9,8 +9,6 @@ // ReSharper disable AccessToDisposedClosure namespace Microsoft.EntityFrameworkCore.Query; -#nullable disable - public abstract class SqlQueryTestBase : QueryTestBase where TFixture : NorthwindQueryRelationalFixture, new() { @@ -141,7 +139,7 @@ public virtual Task SqlQueryRaw_queryable_simple(bool async) async, _ => Fixture.CreateContext().Database.SqlQueryRaw (NormalizeDelimitersInRawString("SELECT * FROM [Customers] WHERE [ContactName] LIKE '%z%'")), - ss => ss.Set().Where(x => x.ContactName.Contains("z")).Select(e => UnmappedCustomer.FromCustomer(e)), + ss => ss.Set().Where(x => x.ContactName!.Contains("z")).Select(e => UnmappedCustomer.FromCustomer(e)), elementSorter: e => e.CustomerID, elementAsserter: AssertUnmappedCustomers); @@ -151,7 +149,7 @@ public virtual Task SqlQueryRaw_queryable_simple_mapped_type(bool async) async, _ => Fixture.CreateContext().Database.SqlQueryRaw (NormalizeDelimitersInRawString("SELECT * FROM [Customers] WHERE [ContactName] LIKE '%z%'")), - ss => ss.Set().Where(x => x.ContactName.Contains("z"))); + ss => ss.Set().Where(x => x.ContactName!.Contains("z"))); [Theory, MemberData(nameof(IsAsyncData))] public virtual Task SqlQueryRaw_queryable_simple_columns_out_of_order(bool async) @@ -211,8 +209,8 @@ public virtual Task SqlQueryRaw_queryable_composed(bool async) async, _ => Fixture.CreateContext().Database.SqlQueryRaw( NormalizeDelimitersInRawString("SELECT * FROM [Customers]")) - .Where(c => c.ContactName.Contains("z")), - ss => ss.Set().Where(c => c.ContactName.Contains("z")).Select(e => UnmappedCustomer.FromCustomer(e)), + .Where(c => c.ContactName!.Contains("z")), + ss => ss.Set().Where(c => c.ContactName!.Contains("z")).Select(e => UnmappedCustomer.FromCustomer(e)), elementSorter: e => e.CustomerID, elementAsserter: AssertUnmappedCustomers); @@ -223,8 +221,8 @@ public virtual Task SqlQueryRaw_queryable_composed_after_removing_whitespaces(bo _ => Fixture.CreateContext().Database.SqlQueryRaw( NormalizeDelimitersInRawString( _eol + " " + _eol + _eol + _eol + "SELECT" + _eol + "* FROM [Customers]")) - .Where(c => c.ContactName.Contains("z")), - ss => ss.Set().Where(c => c.ContactName.Contains("z")).Select(e => UnmappedCustomer.FromCustomer(e)), + .Where(c => c.ContactName!.Contains("z")), + ss => ss.Set().Where(c => c.ContactName!.Contains("z")).Select(e => UnmappedCustomer.FromCustomer(e)), elementSorter: e => e.CustomerID, elementAsserter: AssertUnmappedCustomers); @@ -235,7 +233,7 @@ public virtual async Task SqlQueryRaw_queryable_composed_compiled(bool async) { var query = EF.CompileAsyncQuery((NorthwindContext context) => context.Database.SqlQueryRaw( NormalizeDelimitersInRawString("SELECT * FROM [Customers]")) - .Where(c => c.ContactName.Contains("z"))); + .Where(c => c.ContactName!.Contains("z"))); using (var context = CreateContext()) { @@ -248,7 +246,7 @@ public virtual async Task SqlQueryRaw_queryable_composed_compiled(bool async) { var query = EF.CompileQuery((NorthwindContext context) => context.Database.SqlQueryRaw( NormalizeDelimitersInRawString("SELECT * FROM [Customers]")) - .Where(c => c.ContactName.Contains("z"))); + .Where(c => c.ContactName!.Contains("z"))); using (var context = CreateContext()) { @@ -266,7 +264,7 @@ public virtual async Task SqlQueryRaw_queryable_composed_compiled_with_parameter { var query = EF.CompileAsyncQuery((NorthwindContext context) => context.Database.SqlQueryRaw( NormalizeDelimitersInRawString("SELECT * FROM [Customers] WHERE [CustomerID] = {0}"), "CONSH") - .Where(c => c.ContactName.Contains("z"))); + .Where(c => c.ContactName!.Contains("z"))); using (var context = CreateContext()) { @@ -279,7 +277,7 @@ public virtual async Task SqlQueryRaw_queryable_composed_compiled_with_parameter { var query = EF.CompileQuery((NorthwindContext context) => context.Database.SqlQueryRaw( NormalizeDelimitersInRawString("SELECT * FROM [Customers] WHERE [CustomerID] = {0}"), "CONSH") - .Where(c => c.ContactName.Contains("z"))); + .Where(c => c.ContactName!.Contains("z"))); using (var context = CreateContext()) { @@ -298,7 +296,7 @@ public virtual async Task SqlQueryRaw_queryable_composed_compiled_with_DbParamet var query = EF.CompileAsyncQuery((NorthwindContext context) => context.Database.SqlQueryRaw( NormalizeDelimitersInRawString("SELECT * FROM [Customers] WHERE [CustomerID] = @customer"), CreateDbParameter("customer", "CONSH")) - .Where(c => c.ContactName.Contains("z"))); + .Where(c => c.ContactName!.Contains("z"))); using (var context = CreateContext()) { @@ -312,7 +310,7 @@ public virtual async Task SqlQueryRaw_queryable_composed_compiled_with_DbParamet var query = EF.CompileQuery((NorthwindContext context) => context.Database.SqlQueryRaw( NormalizeDelimitersInRawString("SELECT * FROM [Customers] WHERE [CustomerID] = @customer"), CreateDbParameter("customer", "CONSH")) - .Where(c => c.ContactName.Contains("z"))); + .Where(c => c.ContactName!.Contains("z"))); using (var context = CreateContext()) { @@ -330,8 +328,8 @@ public virtual async Task SqlQueryRaw_queryable_composed_compiled_with_nameless_ { var query = EF.CompileAsyncQuery((NorthwindContext context) => context.Database.SqlQueryRaw( NormalizeDelimitersInRawString("SELECT * FROM [Customers] WHERE [CustomerID] = {0}"), - CreateDbParameter(null, "CONSH")) - .Where(c => c.ContactName.Contains("z"))); + CreateDbParameter(null!, "CONSH")) + .Where(c => c.ContactName!.Contains("z"))); using (var context = CreateContext()) { @@ -344,8 +342,8 @@ public virtual async Task SqlQueryRaw_queryable_composed_compiled_with_nameless_ { var query = EF.CompileQuery((NorthwindContext context) => context.Database.SqlQueryRaw( NormalizeDelimitersInRawString("SELECT * FROM [Customers] WHERE [CustomerID] = {0}"), - CreateDbParameter(null, "CONSH")) - .Where(c => c.ContactName.Contains("z"))); + CreateDbParameter(null!, "CONSH")) + .Where(c => c.ContactName!.Contains("z"))); using (var context = CreateContext()) { @@ -723,7 +721,7 @@ public virtual Task SqlQueryRaw_queryable_simple_as_no_tracking_not_composed(boo public virtual async Task SqlQueryRaw_queryable_simple_projection_composed(bool async) { using var context = CreateContext(); - var boolMapping = (RelationalTypeMapping)context.GetService().FindMapping(typeof(bool)); + var boolMapping = (RelationalTypeMapping)context.GetService().FindMapping(typeof(bool))!; var boolLiteral = boolMapping.GenerateSqlLiteral(true); await AssertQuery( @@ -769,8 +767,8 @@ public virtual Task SqlQueryRaw_composed_with_predicate(bool async) async, _ => Fixture.CreateContext().Database.SqlQueryRaw( NormalizeDelimitersInRawString("SELECT * FROM [Customers]")) - .Where(c => c.ContactName.Substring(0, 1) == c.CompanyName.Substring(0, 1)), - ss => ss.Set().Where(c => c.ContactName.Substring(0, 1) == c.CompanyName.Substring(0, 1)) + .Where(c => c.ContactName!.Substring(0, 1) == c.CompanyName!.Substring(0, 1)), + ss => ss.Set().Where(c => c.ContactName!.Substring(0, 1) == c.CompanyName!.Substring(0, 1)) .Select(e => UnmappedCustomer.FromCustomer(e)), elementSorter: e => e.CustomerID, elementAsserter: AssertUnmappedCustomers); @@ -1023,7 +1021,7 @@ public virtual Task SqlQueryRaw_in_subquery_with_positional_dbParameter_without_ NormalizeDelimitersInRawString("SELECT * FROM [Orders]")).Where(o => context.Database.SqlQueryRaw( NormalizeDelimitersInRawString(@"SELECT * FROM [Customers] WHERE [City] = {0}"), // ReSharper disable once FormatStringProblem - CreateDbParameter(null, "London")) + CreateDbParameter(null!, "London")) .Select(c => c.CustomerID) .Contains(o.CustomerID)), ss => ss.Set().Select(e => UnmappedOrder.FromOrder(e)).Where(o => ss.Set() @@ -1110,8 +1108,8 @@ WITH [Customers2] AS ( ) SELECT * FROM [Customers2] """)) - .Where(c => c.ContactName.Contains("z")), - ss => ss.Set().Where(c => c.ContactName.Contains("z")).Select(e => UnmappedCustomer.FromCustomer(e)), + .Where(c => c.ContactName!.Contains("z")), + ss => ss.Set().Where(c => c.ContactName!.Contains("z")).Select(e => UnmappedCustomer.FromCustomer(e)), elementSorter: e => e.CustomerID, elementAsserter: AssertUnmappedCustomers); @@ -1212,20 +1210,20 @@ public virtual async Task SqlQueryRaw_then_String_ToUpper_String_Length(bool asy protected class Blog { public int Id { get; set; } - public List Posts { get; set; } + public List Posts { get; set; } = null!; } protected class Post { public int Id { get; set; } public int BlogId { get; set; } - public Blog Blog { get; set; } + public Blog Blog { get; set; } = null!; } protected class Person { public int Id { get; set; } - public string Name { get; set; } + public string Name { get; set; } = null!; public ContactInfo Contact { get; set; } } diff --git a/test/EFCore.Relational.Specification.Tests/Query/UdfDbFunctionTestBase.cs b/test/EFCore.Relational.Specification.Tests/Query/UdfDbFunctionTestBase.cs index f1036a8373c..9dfbb2f1844 100644 --- a/test/EFCore.Relational.Specification.Tests/Query/UdfDbFunctionTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/Query/UdfDbFunctionTestBase.cs @@ -6,8 +6,6 @@ namespace Microsoft.EntityFrameworkCore.Query; -#nullable disable - public abstract class UdfDbFunctionTestBase(TFixture fixture) : IClassFixture where TFixture : SharedStoreFixtureBase, new() { @@ -34,22 +32,22 @@ public Phone(int code, int number) public class Customer { public int Id { get; set; } - public string FirstName { get; set; } - public string LastName { get; set; } - public List Orders { get; set; } - public List
Addresses { get; set; } + public string? FirstName { get; set; } + public string? LastName { get; set; } + public List Orders { get; set; } = null!; + public List
Addresses { get; set; } = null!; } public class Order { public int Id { get; set; } - public string Name { get; set; } + public string Name { get; set; } = null!; public DateTime OrderDate { get; set; } public int CustomerId { get; set; } - public Customer Customer { get; set; } - public List Items { get; set; } + public Customer Customer { get; set; } = null!; + public List Items { get; set; } = null!; } public class LineItem @@ -59,25 +57,25 @@ public class LineItem public int ProductId { get; set; } public int Quantity { get; set; } - public Order Order { get; set; } - public Product Product { get; set; } + public Order Order { get; set; } = null!; + public Product Product { get; set; } = null!; } public class Product { public int Id { get; set; } - public string Name { get; set; } + public string Name { get; set; } = null!; } public class Address { public int Id { get; set; } - public string Street { get; set; } - public string City { get; set; } - public string State { get; set; } + public string Street { get; set; } = null!; + public string? City { get; set; } + public string? State { get; set; } public int CustomerId { get; set; } - public Customer Customer { get; set; } + public Customer Customer { get; set; } = null!; } public class OrderByYear @@ -91,7 +89,7 @@ public class MultProductOrders { public int OrderId { get; set; } - public Customer Customer { get; set; } + public Customer Customer { get; set; } = null!; public int CustomerId { get; set; } public DateTime OrderDate { get; set; } @@ -99,7 +97,7 @@ public class MultProductOrders public class TopSellingProduct { - public Product Product { get; set; } + public Product Product { get; set; } = null!; public int? ProductId { get; set; } public int? AmountSold { get; set; } @@ -121,31 +119,31 @@ public ComplexGpsCoordinates(double latitude, double longitude) public class MapLocation { public int Id { get; set; } - public ComplexGpsCoordinates GpsCoordinates { get; set; } + public ComplexGpsCoordinates GpsCoordinates { get; set; } = null!; } public class MapLocationData { public int Id { get; set; } - public ComplexGpsCoordinates GpsCoordinates { get; set; } + public ComplexGpsCoordinates GpsCoordinates { get; set; } = null!; } public class CustomerData { public int Id { get; set; } - public string FirstName { get; set; } - public string LastName { get; set; } + public string FirstName { get; set; } = null!; + public string LastName { get; set; } = null!; } protected class UDFSqlContext(DbContextOptions options) : PoolableDbContext(options) { #region DbSets - public DbSet Customers { get; set; } - public DbSet Orders { get; set; } - public DbSet Products { get; set; } - public DbSet
Addresses { get; set; } - public DbSet MapLocations { get; set; } + public DbSet Customers { get; set; } = null!; + public DbSet Orders { get; set; } = null!; + public DbSet Products { get; set; } = null!; + public DbSet
Addresses { get; set; } = null!; + public DbSet MapLocations { get; set; } = null!; #endregion @@ -299,42 +297,42 @@ public IQueryable GetCustomerData(int customerId) protected override void OnModelCreating(ModelBuilder modelBuilder) { //Static - modelBuilder.HasDbFunction(typeof(UDFSqlContext).GetMethod(nameof(CustomerOrderCountStatic))).HasName("CustomerOrderCount"); - modelBuilder.HasDbFunction(typeof(UDFSqlContext).GetMethod(nameof(CustomerOrderCountWithClientStatic))) + modelBuilder.HasDbFunction(typeof(UDFSqlContext).GetMethod(nameof(CustomerOrderCountStatic))!).HasName("CustomerOrderCount"); + modelBuilder.HasDbFunction(typeof(UDFSqlContext).GetMethod(nameof(CustomerOrderCountWithClientStatic))!) .HasName("CustomerOrderCount"); - modelBuilder.HasDbFunction(typeof(UDFSqlContext).GetMethod(nameof(StarValueStatic))).HasName("StarValue"); - modelBuilder.HasDbFunction(typeof(UDFSqlContext).GetMethod(nameof(IsTopCustomerStatic))).HasName("IsTopCustomer"); - modelBuilder.HasDbFunction(typeof(UDFSqlContext).GetMethod(nameof(GetCustomerWithMostOrdersAfterDateStatic))) + modelBuilder.HasDbFunction(typeof(UDFSqlContext).GetMethod(nameof(StarValueStatic))!).HasName("StarValue"); + modelBuilder.HasDbFunction(typeof(UDFSqlContext).GetMethod(nameof(IsTopCustomerStatic))!).HasName("IsTopCustomer"); + modelBuilder.HasDbFunction(typeof(UDFSqlContext).GetMethod(nameof(GetCustomerWithMostOrdersAfterDateStatic))!) .HasName("GetCustomerWithMostOrdersAfterDate"); - modelBuilder.HasDbFunction(typeof(UDFSqlContext).GetMethod(nameof(GetReportingPeriodStartDateStatic))) + modelBuilder.HasDbFunction(typeof(UDFSqlContext).GetMethod(nameof(GetReportingPeriodStartDateStatic))!) .HasName("GetReportingPeriodStartDate"); - modelBuilder.HasDbFunction(typeof(UDFSqlContext).GetMethod(nameof(GetSqlFragmentStatic))) + modelBuilder.HasDbFunction(typeof(UDFSqlContext).GetMethod(nameof(GetSqlFragmentStatic))!) .HasTranslation(args => new SqlFragmentExpression("'Two'")); - var isDateMethodInfo = typeof(UDFSqlContext).GetMethod(nameof(IsDateStatic)); + var isDateMethodInfo = typeof(UDFSqlContext).GetMethod(nameof(IsDateStatic))!; modelBuilder.HasDbFunction(isDateMethodInfo).HasName("IsDate").IsBuiltIn(); - modelBuilder.HasDbFunction(typeof(UDFSqlContext).GetMethod(nameof(AddValues), [typeof(int), typeof(int)])); + modelBuilder.HasDbFunction(typeof(UDFSqlContext).GetMethod(nameof(AddValues), [typeof(int), typeof(int)])!); - modelBuilder.HasDbFunction(typeof(UDFSqlContext).GetMethod(nameof(IdentityStringPropagateNull), [typeof(string)])) + modelBuilder.HasDbFunction(typeof(UDFSqlContext).GetMethod(nameof(IdentityStringPropagateNull), [typeof(string)])!) .HasParameter("s").PropagatesNullability(); modelBuilder.HasDbFunction( - typeof(UDFSqlContext).GetMethod(nameof(IdentityStringNonNullableFluent), [typeof(string)])) + typeof(UDFSqlContext).GetMethod(nameof(IdentityStringNonNullableFluent), [typeof(string)])!) .IsNullable(false); var abc = new[] { "A", "B", "C" }; - modelBuilder.HasDbFunction(typeof(UDFSqlContext).GetMethod(nameof(IsABC), [typeof(string)])) + modelBuilder.HasDbFunction(typeof(UDFSqlContext).GetMethod(nameof(IsABC), [typeof(string)])!) .HasTranslation(args => new InExpression( args.First(), [ new SqlConstantExpression(abc[0], typeMapping: null), new SqlConstantExpression(abc[1], typeMapping: null), - new SqlConstantExpression(abc[2], typeMapping: null) + new SqlConstantExpression(abc[2], typeMapping: null!) ], // args.First().TypeMapping) - typeMapping: null)); + typeMapping: null!)); var trueFalse = new[] { true, false }; - modelBuilder.HasDbFunction(typeof(UDFSqlContext).GetMethod(nameof(IsOrIsNotABC), [typeof(string)])) + modelBuilder.HasDbFunction(typeof(UDFSqlContext).GetMethod(nameof(IsOrIsNotABC), [typeof(string)])!) .HasTranslation(args => new InExpression( new InExpression( args.First(), @@ -343,14 +341,14 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) new SqlConstantExpression(abc[1], args.First().TypeMapping), new SqlConstantExpression(abc[2], args.First().TypeMapping) ], - typeMapping: null), + typeMapping: null!), [ new SqlConstantExpression(trueFalse[0], typeMapping: null), new SqlConstantExpression(trueFalse[1], typeMapping: null) ], - typeMapping: null)); + typeMapping: null!)); - modelBuilder.HasDbFunction(typeof(UDFSqlContext).GetMethod(nameof(NullableValueReturnType), [])) + modelBuilder.HasDbFunction(typeof(UDFSqlContext).GetMethod(nameof(NullableValueReturnType), [])!) .HasTranslation(_ => new SqlFunctionExpression( "foo", nullable: true, @@ -358,38 +356,38 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) typeMapping: null)); //Instance - modelBuilder.HasDbFunction(typeof(UDFSqlContext).GetMethod(nameof(CustomerOrderCountInstance))) + modelBuilder.HasDbFunction(typeof(UDFSqlContext).GetMethod(nameof(CustomerOrderCountInstance))!) .HasName("CustomerOrderCount"); - modelBuilder.HasDbFunction(typeof(UDFSqlContext).GetMethod(nameof(CustomerOrderCountWithClientInstance))) + modelBuilder.HasDbFunction(typeof(UDFSqlContext).GetMethod(nameof(CustomerOrderCountWithClientInstance))!) .HasName("CustomerOrderCount"); - modelBuilder.HasDbFunction(typeof(UDFSqlContext).GetMethod(nameof(StarValueInstance))).HasName("StarValue"); - modelBuilder.HasDbFunction(typeof(UDFSqlContext).GetMethod(nameof(IsTopCustomerInstance))).HasName("IsTopCustomer"); - modelBuilder.HasDbFunction(typeof(UDFSqlContext).GetMethod(nameof(GetCustomerWithMostOrdersAfterDateInstance))) + modelBuilder.HasDbFunction(typeof(UDFSqlContext).GetMethod(nameof(StarValueInstance))!).HasName("StarValue"); + modelBuilder.HasDbFunction(typeof(UDFSqlContext).GetMethod(nameof(IsTopCustomerInstance))!).HasName("IsTopCustomer"); + modelBuilder.HasDbFunction(typeof(UDFSqlContext).GetMethod(nameof(GetCustomerWithMostOrdersAfterDateInstance))!) .HasName("GetCustomerWithMostOrdersAfterDate"); - modelBuilder.HasDbFunction(typeof(UDFSqlContext).GetMethod(nameof(GetReportingPeriodStartDateInstance))) + modelBuilder.HasDbFunction(typeof(UDFSqlContext).GetMethod(nameof(GetReportingPeriodStartDateInstance))!) .HasName("GetReportingPeriodStartDate"); - var isDateMethodInfo2 = typeof(UDFSqlContext).GetMethod(nameof(IsDateInstance)); + var isDateMethodInfo2 = typeof(UDFSqlContext).GetMethod(nameof(IsDateInstance))!; modelBuilder.HasDbFunction(isDateMethodInfo2).HasName("IsDate").IsBuiltIn(); - modelBuilder.HasDbFunction(typeof(UDFSqlContext).GetMethod(nameof(DollarValueInstance))).HasName("DollarValue"); + modelBuilder.HasDbFunction(typeof(UDFSqlContext).GetMethod(nameof(DollarValueInstance))!).HasName("DollarValue"); - var methodInfo2 = typeof(UDFSqlContext).GetMethod(nameof(MyCustomLengthInstance)); + var methodInfo2 = typeof(UDFSqlContext).GetMethod(nameof(MyCustomLengthInstance))!; modelBuilder.HasDbFunction(methodInfo2).HasName("len").IsBuiltIn(); modelBuilder.Entity().ToTable("MultProductOrders").HasKey(mpo => mpo.OrderId); - modelBuilder.HasDbFunction(typeof(UDFSqlContext).GetMethod(nameof(StringLength), [typeof(string)])) + modelBuilder.HasDbFunction(typeof(UDFSqlContext).GetMethod(nameof(StringLength), [typeof(string)])!) .HasParameter("s").PropagatesNullability(); //Table - modelBuilder.HasDbFunction(typeof(UDFSqlContext).GetMethod(nameof(GetCustomerOrderCountByYear), [typeof(int)])); + modelBuilder.HasDbFunction(typeof(UDFSqlContext).GetMethod(nameof(GetCustomerOrderCountByYear), [typeof(int)])!); modelBuilder.HasDbFunction( - typeof(UDFSqlContext).GetMethod(nameof(GetCustomerOrderCountByYearOnlyFrom2000), [typeof(int), typeof(bool)])); - modelBuilder.HasDbFunction(typeof(UDFSqlContext).GetMethod(nameof(GetTopTwoSellingProducts))); - modelBuilder.HasDbFunction(typeof(UDFSqlContext).GetMethod(nameof(GetTopSellingProductsForCustomer))); - modelBuilder.HasDbFunction(typeof(UDFSqlContext).GetMethod(nameof(GetOrdersWithMultipleProducts))); - modelBuilder.HasDbFunction(typeof(UDFSqlContext).GetMethod(nameof(GetCustomerData))); + typeof(UDFSqlContext).GetMethod(nameof(GetCustomerOrderCountByYearOnlyFrom2000), [typeof(int), typeof(bool)])!); + modelBuilder.HasDbFunction(typeof(UDFSqlContext).GetMethod(nameof(GetTopTwoSellingProducts))!); + modelBuilder.HasDbFunction(typeof(UDFSqlContext).GetMethod(nameof(GetTopSellingProductsForCustomer))!); + modelBuilder.HasDbFunction(typeof(UDFSqlContext).GetMethod(nameof(GetOrdersWithMultipleProducts))!); + modelBuilder.HasDbFunction(typeof(UDFSqlContext).GetMethod(nameof(GetCustomerData))!); modelBuilder.Entity().HasNoKey(); modelBuilder.Entity().HasNoKey().ToFunction("GetTopTwoSellingProducts"); @@ -584,7 +582,7 @@ public virtual void Scalar_Function_Extension_Method_Static() { using var context = CreateContext(); - var len = context.Customers.Count(c => UDFSqlContext.IsDateStatic(c.FirstName) == false); + var len = context.Customers.Count(c => UDFSqlContext.IsDateStatic(c.FirstName!) == false); Assert.Equal(4, len); } @@ -596,7 +594,7 @@ public virtual void Scalar_Function_With_Translator_Translates_Static() var customerId = 3; var len = context.Customers.Where(c => c.Id == customerId) - .Select(c => UDFSqlContext.MyCustomLengthStatic(c.LastName)).Single(); + .Select(c => UDFSqlContext.MyCustomLengthStatic(c.LastName!)).Single(); Assert.Equal(5, len); } @@ -972,7 +970,7 @@ public virtual void Nullable_navigation_property_access_preserves_schema_for_sql var result = context.Orders .OrderBy(o => o.Id) - .Select(o => UDFSqlContext.IdentityString(o.Customer.FirstName)) + .Select(o => UDFSqlContext.IdentityString(o.Customer.FirstName!)) .FirstOrDefault(); Assert.Equal("Customer", result); @@ -985,7 +983,7 @@ public virtual void Compare_function_without_null_propagation_to_null() var result = context.Customers .OrderBy(c => c.Id) - .Where(c => UDFSqlContext.IdentityString(c.FirstName) != null) + .Where(c => UDFSqlContext.IdentityString(c.FirstName!) != null) .ToList(); Assert.Equal(4, result.Count); @@ -998,7 +996,7 @@ public virtual void Compare_function_with_null_propagation_to_null() var result = context.Customers .OrderBy(c => c.Id) - .Where(c => UDFSqlContext.IdentityStringPropagateNull(c.FirstName) != null) + .Where(c => UDFSqlContext.IdentityStringPropagateNull(c.FirstName!) != null) .ToList(); Assert.Equal(4, result.Count); @@ -1011,8 +1009,8 @@ public virtual void Compare_non_nullable_function_to_null_gets_optimized() var result = context.Customers .OrderBy(c => c.Id) - .Where(c => UDFSqlContext.IdentityStringNonNullable(c.FirstName) != null - && UDFSqlContext.IdentityStringNonNullableFluent(c.FirstName) != null) + .Where(c => UDFSqlContext.IdentityStringNonNullable(c.FirstName!) != null + && UDFSqlContext.IdentityStringNonNullableFluent(c.FirstName!) != null) .ToList(); Assert.Equal(4, result.Count); @@ -1025,7 +1023,7 @@ public virtual void Compare_functions_returning_int_that_take_nullable_param_whi var result = context.Customers .OrderBy(c => c.Id) - .Where(c => context.StringLength(c.FirstName) != context.StringLength(c.LastName)) + .Where(c => context.StringLength(c.FirstName!) != context.StringLength(c.LastName!)) .ToList(); Assert.Equal(4, result.Count); @@ -1045,7 +1043,7 @@ public virtual void Scalar_Function_SqlFragment_Static() public virtual void Scalar_Function_with_InExpression_translation() { using var context = CreateContext(); - var query = context.Customers.Where(c => UDFSqlContext.IsABC(c.FirstName.Substring(0, 1))).ToList(); + var query = context.Customers.Where(c => UDFSqlContext.IsABC(c.FirstName!.Substring(0, 1))).ToList(); Assert.Equal(4, query.Count); } @@ -1054,7 +1052,7 @@ public virtual void Scalar_Function_with_InExpression_translation() public virtual void Scalar_Function_with_nested_InExpression_translation() { using var context = CreateContext(); - var query = context.Customers.Where(c => UDFSqlContext.IsOrIsNotABC(c.FirstName.Substring(0, 1))).ToList(); + var query = context.Customers.Where(c => UDFSqlContext.IsOrIsNotABC(c.FirstName!.Substring(0, 1))).ToList(); Assert.Equal(4, query.Count); } @@ -1087,7 +1085,7 @@ public virtual void Scalar_Function_Non_Static() var custName = (from c in context.Customers where c.Id == 1 - select new { Id = context.StarValueInstance(4, c.Id), LastName = context.DollarValueInstance(2, c.LastName) }) + select new { Id = context.StarValueInstance(4, c.Id), LastName = context.DollarValueInstance(2, c.LastName!) }) .Single(); Assert.Equal("$$One", custName.LastName); @@ -1098,7 +1096,7 @@ public virtual void Scalar_Function_Extension_Method_Instance() { using var context = CreateContext(); - var len = context.Customers.Count(c => context.IsDateInstance(c.FirstName) == false); + var len = context.Customers.Count(c => context.IsDateInstance(c.FirstName!) == false); Assert.Equal(4, len); } @@ -1110,7 +1108,7 @@ public virtual void Scalar_Function_With_Translator_Translates_Instance() var customerId = 3; var len = context.Customers.Where(c => c.Id == customerId) - .Select(c => context.MyCustomLengthInstance(c.LastName)).Single(); + .Select(c => context.MyCustomLengthInstance(c.LastName!)).Single(); Assert.Equal(5, len); } @@ -2120,7 +2118,7 @@ public virtual void TVF_with_navigation_in_projection_groupby_aggregate() .Where(c => !context.Set().Select(x => x.ProductId).Contains(25)) .Select(x => new { x.Customer.FirstName, x.Customer.LastName }) .GroupBy(x => new { x.LastName }) - .Select(x => new { x.Key.LastName, SumOfLengths = x.Sum(xx => xx.FirstName.Length) }) + .Select(x => new { x.Key.LastName, SumOfLengths = x.Sum(xx => xx.FirstName!.Length) }) .ToList(); Assert.Equal(3, query.Count); @@ -2138,11 +2136,11 @@ public virtual void TVF_with_argument_being_a_subquery_with_navigation_in_projec { using var context = CreateContext(); var query = context.Orders - .Where(c => !context.GetOrdersWithMultipleProducts(context.Customers.OrderBy(x => x.Id).FirstOrDefault().Id) + .Where(c => !context.GetOrdersWithMultipleProducts(context.Customers.OrderBy(x => x.Id).FirstOrDefault()!.Id) .Select(x => x.CustomerId).Contains(25)) .Select(x => new { x.Customer.FirstName, x.Customer.LastName }) .GroupBy(x => new { x.LastName }) - .Select(x => new { x.Key.LastName, SumOfLengths = x.Sum(xx => xx.FirstName.Length) }) + .Select(x => new { x.Key.LastName, SumOfLengths = x.Sum(xx => xx.FirstName!.Length) }) .ToList(); Assert.Equal(3, query.Count); diff --git a/test/EFCore.Relational.Specification.Tests/Query/WarningsTestBase.cs b/test/EFCore.Relational.Specification.Tests/Query/WarningsTestBase.cs index d13d9d3e052..c14b73796e7 100644 --- a/test/EFCore.Relational.Specification.Tests/Query/WarningsTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/Query/WarningsTestBase.cs @@ -10,8 +10,6 @@ namespace Microsoft.EntityFrameworkCore.Query; -#nullable disable - public abstract class WarningsTestBase : IClassFixture where TFixture : NorthwindQueryRelationalFixture, new() { @@ -53,7 +51,7 @@ public virtual async Task Paging_operation_without_orderby_issues_warning_async( public virtual void FirstOrDefault_without_orderby_and_filter_issues_warning_subquery() { using var context = CreateContext(); - var query = context.Customers.Where(c => c.CustomerID == "ALFKI" && c.Orders.FirstOrDefault().OrderID > 1000).ToList(); + var query = context.Customers.Where(c => c.CustomerID == "ALFKI" && c.Orders.FirstOrDefault()!.OrderID > 1000).ToList(); Assert.Single(query); } @@ -81,7 +79,7 @@ public virtual void LastOrDefault_with_order_by_does_not_issue_client_eval_warni { using var context = CreateContext(); var query1 = context.Customers - .Where(c => c.CustomerID == "ALFKI" && c.Orders.OrderBy(o => o.OrderID).LastOrDefault().OrderID > 1000).ToList(); + .Where(c => c.CustomerID == "ALFKI" && c.Orders.OrderBy(o => o.OrderID).LastOrDefault()!.OrderID > 1000).ToList(); Assert.NotNull(query1); var query2 = context.Customers.OrderBy(c => c.CustomerID).LastOrDefault(); diff --git a/test/EFCore.Relational.Specification.Tests/RelationalComplianceTestBase.cs b/test/EFCore.Relational.Specification.Tests/RelationalComplianceTestBase.cs index 31b7bc1ded8..05817d29471 100644 --- a/test/EFCore.Relational.Specification.Tests/RelationalComplianceTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/RelationalComplianceTestBase.cs @@ -3,8 +3,6 @@ namespace Microsoft.EntityFrameworkCore; -#nullable disable - public abstract class RelationalComplianceTestBase : ComplianceTestBase { protected override IEnumerable GetBaseTestClasses() diff --git a/test/EFCore.Relational.Specification.Tests/RelationalServiceCollectionExtensionsTestBase.cs b/test/EFCore.Relational.Specification.Tests/RelationalServiceCollectionExtensionsTestBase.cs index 8d82c356ee1..da5396d7c7e 100644 --- a/test/EFCore.Relational.Specification.Tests/RelationalServiceCollectionExtensionsTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/RelationalServiceCollectionExtensionsTestBase.cs @@ -3,8 +3,6 @@ namespace Microsoft.EntityFrameworkCore; -#nullable disable - public abstract class RelationalServiceCollectionExtensionsTestBase(TestHelpers testHelpers) : EntityFrameworkServiceCollectionExtensionsTestBase(testHelpers) { diff --git a/test/EFCore.Relational.Specification.Tests/StoreGeneratedFixupRelationalTestBase.cs b/test/EFCore.Relational.Specification.Tests/StoreGeneratedFixupRelationalTestBase.cs index ea2da2ce985..a4d02c1a2a2 100644 --- a/test/EFCore.Relational.Specification.Tests/StoreGeneratedFixupRelationalTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/StoreGeneratedFixupRelationalTestBase.cs @@ -3,8 +3,6 @@ namespace Microsoft.EntityFrameworkCore; -#nullable disable - public abstract class StoreGeneratedFixupRelationalTestBase(TFixture fixture) : StoreGeneratedFixupTestBase(fixture) where TFixture : StoreGeneratedFixupRelationalTestBase.StoreGeneratedFixupRelationalFixtureBase, new() { diff --git a/test/EFCore.Relational.Specification.Tests/TPTTableSplittingTestBase.cs b/test/EFCore.Relational.Specification.Tests/TPTTableSplittingTestBase.cs index 8202b76dc4d..3c7a4895a74 100644 --- a/test/EFCore.Relational.Specification.Tests/TPTTableSplittingTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/TPTTableSplittingTestBase.cs @@ -6,8 +6,6 @@ // ReSharper disable InconsistentNaming namespace Microsoft.EntityFrameworkCore; -#nullable disable - public abstract class TPTTableSplittingTestBase(NonSharedFixture fixture, ITestOutputHelper testOutputHelper) : TableSplittingTestBase(fixture, testOutputHelper) { diff --git a/test/EFCore.Relational.Specification.Tests/TableSplittingTestBase.cs b/test/EFCore.Relational.Specification.Tests/TableSplittingTestBase.cs index b0ac1f331b5..4d7e7fbe898 100644 --- a/test/EFCore.Relational.Specification.Tests/TableSplittingTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/TableSplittingTestBase.cs @@ -7,8 +7,6 @@ // ReSharper disable InconsistentNaming namespace Microsoft.EntityFrameworkCore; -#nullable disable - public abstract class TableSplittingTestBase : NonSharedModelTestBase, IClassFixture { protected TableSplittingTestBase(NonSharedFixture fixture, ITestOutputHelper testOutputHelper) @@ -138,7 +136,7 @@ await InitializeAsync( Operator = new Operator { Name = "Kai Saunders" } }); - scooterEntry.Reference(v => v.Engine).TargetEntry.Property("SeatingCapacity").CurrentValue = 1; + scooterEntry.Reference(v => v.Engine).TargetEntry!.Property("SeatingCapacity").CurrentValue = 1; context.SaveChanges(); } @@ -147,7 +145,7 @@ await InitializeAsync( { var scooter = context.Set().Include(v => v.Engine).Single(v => v.Name == "Electric scooter"); - Assert.Equal(scooter.SeatingCapacity, context.Entry(scooter.Engine).Property("SeatingCapacity").CurrentValue); + Assert.Equal(scooter.SeatingCapacity, context.Entry(scooter.Engine!).Property("SeatingCapacity").CurrentValue); } } @@ -179,7 +177,7 @@ await InitializeAsync( Assert.Equal( scooterEntry.Entity.SeatingCapacity, - scooterEntry.Reference(v => (IntermittentCombustionEngine)v.Engine).TargetEntry + scooterEntry.Reference(v => (IntermittentCombustionEngine)v.Engine!).TargetEntry! .ComplexProperty(v => v.FuelTank).Property("SeatingCapacity").CurrentValue); } @@ -188,7 +186,7 @@ await InitializeAsync( var scooter = context.Set().Include(v => v.Engine).Single(v => v.Name == "Gas scooter"); Assert.Equal( - scooter.SeatingCapacity, context.Entry(scooter).Reference(v => (IntermittentCombustionEngine)v.Engine).TargetEntry + scooter.SeatingCapacity, context.Entry(scooter).Reference(v => (IntermittentCombustionEngine)v.Engine!).TargetEntry! .ComplexProperty(v => v.FuelTank).Property("SeatingCapacity").CurrentValue); } } @@ -244,7 +242,7 @@ await InitializeAsync( { var scooter = context.Set().Include(v => v.Engine).Single(v => v.Name == "Electric scooter"); - Assert.Equal(scooter.SeatingCapacity, context.Entry(scooter.Engine).Property("SeatingCapacity").CurrentValue); + Assert.Equal(scooter.SeatingCapacity, context.Entry(scooter.Engine!).Property("SeatingCapacity").CurrentValue); scooter.SeatingCapacity = 2; context.SaveChanges(); @@ -255,7 +253,7 @@ await InitializeAsync( var scooter = context.Set().Include(v => v.Engine).Single(v => v.Name == "Electric scooter"); Assert.Equal(2, scooter.SeatingCapacity); - Assert.Equal(2, context.Entry(scooter.Engine).Property("SeatingCapacity").CurrentValue); + Assert.Equal(2, context.Entry(scooter.Engine!).Property("SeatingCapacity").CurrentValue); } } @@ -299,7 +297,7 @@ await InitializeAsync( scooter.Engine = new IntermittentCombustionEngine { FuelTank = new FuelTank { Capacity = 5 } }; - var seatingCapacityEntry = context.Entry(scooter).Reference(v => (IntermittentCombustionEngine)v.Engine).TargetEntry + var seatingCapacityEntry = context.Entry(scooter).Reference(v => (IntermittentCombustionEngine)v.Engine!).TargetEntry! .ComplexProperty(v => v.FuelTank).Property("SeatingCapacity"); Assert.Equal(0, seatingCapacityEntry.OriginalValue); @@ -316,7 +314,7 @@ await InitializeAsync( var scooter = context.Set().Include(v => v.Engine).Single(v => v.Name == "Gas scooter"); Assert.Equal( - scooter.SeatingCapacity, context.Entry(scooter).Reference(v => (IntermittentCombustionEngine)v.Engine).TargetEntry + scooter.SeatingCapacity, context.Entry(scooter).Reference(v => (IntermittentCombustionEngine)v.Engine!).TargetEntry! .ComplexProperty(v => v.FuelTank).Property("SeatingCapacity").CurrentValue); scooter.SeatingCapacity = 2; @@ -329,7 +327,7 @@ await InitializeAsync( Assert.Equal(2, scooter.SeatingCapacity); Assert.Equal( - 2, context.Entry(scooter).Reference(v => (IntermittentCombustionEngine)v.Engine).TargetEntry + 2, context.Entry(scooter).Reference(v => (IntermittentCombustionEngine)v.Engine!).TargetEntry! .ComplexProperty(v => v.FuelTank).Property("SeatingCapacity").CurrentValue); } } @@ -370,7 +368,7 @@ await InitializeAsync(modelBuilder => var streetcarFromStore = context.Set().Include(v => v.Engine).AsNoTracking() .Single(v => v.Name == "1984 California Car"); - Assert.Equal("Streetcar engine", streetcarFromStore.Engine.Description); + Assert.Equal("Streetcar engine", streetcarFromStore.Engine!.Description); streetcarFromStore.Engine.Description = "Line"; @@ -383,7 +381,7 @@ await InitializeAsync(modelBuilder => var streetcarFromStore = context.Set().Include(v => v.Engine) .Single(v => v.Name == "1984 California Car"); - Assert.Equal("Line", streetcarFromStore.Engine.Description); + Assert.Equal("Line", streetcarFromStore.Engine!.Description); streetcarFromStore.SeatingCapacity = 40; streetcarFromStore.Engine.Description = "Streetcar engine"; @@ -397,7 +395,7 @@ await InitializeAsync(modelBuilder => .Single(v => v.Name == "1984 California Car"); Assert.Equal(40, streetcarFromStore.SeatingCapacity); - Assert.Equal("Streetcar engine", streetcarFromStore.Engine.Description); + Assert.Equal("Streetcar engine", streetcarFromStore.Engine!.Description); context.Remove(streetcarFromStore.Engine); @@ -639,9 +637,9 @@ public virtual async Task Optional_dependent_materialized_when_no_properties() var vehicle = context.Set() .Where(e => e.Name == "AIM-9M Sidewinder") .OrderBy(e => e.Name) - .Include(e => e.Operator.Details).First(); + .Include(e => e.Operator!.Details).First(); Assert.Equal(0, vehicle.SeatingCapacity); - Assert.Equal("Heat-seeking", vehicle.Operator.Details.Type); + Assert.Equal("Heat-seeking", vehicle.Operator!.Details!.Type); Assert.Null(vehicle.Operator.Name); } @@ -842,16 +840,16 @@ public class DetailedOrder { public int Id { get; set; } public OrderStatus? Status { get; set; } - public string BillingAddress { get; set; } - public string ShippingAddress { get; set; } - public byte[] Version { get; set; } + public string? BillingAddress { get; set; } + public string? ShippingAddress { get; set; } + public byte[] Version { get; set; } = null!; } public class Order { public int Id { get; set; } public OrderStatus? Status { get; set; } - public DetailedOrder DetailedOrder { get; set; } + public DetailedOrder? DetailedOrder { get; set; } } public enum OrderStatus @@ -869,8 +867,8 @@ protected override string NonSharedStoreName protected TestSqlLoggerFactory TestSqlLoggerFactory => (TestSqlLoggerFactory)ListLoggerFactory; - protected ContextFactory ContextFactory { get; private set; } - protected ContextFactory SharedContextFactory { get; private set; } + protected ContextFactory? ContextFactory { get; private set; } + protected ContextFactory? SharedContextFactory { get; private set; } protected void AssertSql(params string[] expected) => TestSqlLoggerFactory.AssertBaseline(expected); @@ -950,10 +948,10 @@ protected async Task InitializeSharedAsync(Action onModelCreating, .EnableSensitiveDataLogging(sensitiveLogEnabled)); protected virtual TransportationContext CreateContext() - => ContextFactory.CreateDbContext(); + => ContextFactory!.CreateDbContext(); protected virtual SharedTableContext CreateSharedContext() - => SharedContextFactory.CreateDbContext(); + => SharedContextFactory!.CreateDbContext(); public override async ValueTask DisposeAsync() { @@ -965,23 +963,23 @@ public override async ValueTask DisposeAsync() protected class SharedTableContext(DbContextOptions options) : PoolableDbContext(options) { - public DbSet MeterReadings { get; set; } - public DbSet MeterReadingDetails { get; set; } + public DbSet MeterReadings { get; set; } = null!; + public DbSet MeterReadingDetails { get; set; } = null!; } protected class MeterReading { public int Id { get; set; } public MeterReadingStatus? ReadingStatus { get; set; } - public MeterReadingDetail MeterReadingDetails { get; set; } + public MeterReadingDetail? MeterReadingDetails { get; set; } } protected class MeterReadingDetail { public int Id { get; set; } public MeterReadingStatus? ReadingStatus { get; set; } - public string CurrentRead { get; set; } - public string PreviousRead { get; set; } + public string? CurrentRead { get; set; } + public string? PreviousRead { get; set; } } protected enum MeterReadingStatus diff --git a/test/EFCore.Relational.Specification.Tests/TestModels/EntitySplitting/EntitySplittingContext.cs b/test/EFCore.Relational.Specification.Tests/TestModels/EntitySplitting/EntitySplittingContext.cs index 0d69d1341d4..91400added1 100644 --- a/test/EFCore.Relational.Specification.Tests/TestModels/EntitySplitting/EntitySplittingContext.cs +++ b/test/EFCore.Relational.Specification.Tests/TestModels/EntitySplitting/EntitySplittingContext.cs @@ -3,6 +3,4 @@ namespace Microsoft.EntityFrameworkCore.TestModels.EntitySplitting; -#nullable disable - public class EntitySplittingContext(DbContextOptions options) : PoolableDbContext(options); diff --git a/test/EFCore.Relational.Specification.Tests/TestModels/EntitySplitting/EntitySplittingData.cs b/test/EFCore.Relational.Specification.Tests/TestModels/EntitySplitting/EntitySplittingData.cs index 19f40ddfa6d..d5f5291c6a4 100644 --- a/test/EFCore.Relational.Specification.Tests/TestModels/EntitySplitting/EntitySplittingData.cs +++ b/test/EFCore.Relational.Specification.Tests/TestModels/EntitySplitting/EntitySplittingData.cs @@ -3,8 +3,6 @@ namespace Microsoft.EntityFrameworkCore.TestModels.EntitySplitting; -#nullable disable - public class EntitySplittingData : ISetSource { public static readonly EntitySplittingData Instance = new(); diff --git a/test/EFCore.Relational.Specification.Tests/TestModels/EntitySplitting/EntitySplittingTypes.cs b/test/EFCore.Relational.Specification.Tests/TestModels/EntitySplitting/EntitySplittingTypes.cs index d9999470733..48d0606a24e 100644 --- a/test/EFCore.Relational.Specification.Tests/TestModels/EntitySplitting/EntitySplittingTypes.cs +++ b/test/EFCore.Relational.Specification.Tests/TestModels/EntitySplitting/EntitySplittingTypes.cs @@ -5,24 +5,22 @@ namespace Microsoft.EntityFrameworkCore.TestModels.EntitySplitting; -#nullable disable - public class EntityOne { public int Id { get; set; } - public string StringValue1 { get; set; } - public string StringValue2 { get; set; } - public string StringValue3 { get; set; } - public string StringValue4 { get; set; } + public string? StringValue1 { get; set; } + public string? StringValue2 { get; set; } + public string? StringValue3 { get; set; } + public string? StringValue4 { get; set; } public int IntValue1 { get; set; } public int IntValue2 { get; set; } public int IntValue3 { get; set; } public int IntValue4 { get; set; } public List EntityTwos { get; set; } = []; - public EntityThree EntityThree { get; set; } + public EntityThree? EntityThree { get; set; } [NotMapped] - public OwnedReference OwnedReference { get; set; } + public OwnedReference? OwnedReference { get; set; } [NotMapped] public List OwnedCollection { get; set; } = []; @@ -31,31 +29,31 @@ public class EntityOne public class EntityTwo { public int Id { get; set; } - public string Name { get; set; } - public EntityOne EntityOne { get; set; } + public string? Name { get; set; } + public EntityOne? EntityOne { get; set; } } public class EntityThree { public int Id { get; set; } - public string Name { get; set; } + public string? Name { get; set; } public List EntityOnes { get; set; } = []; } public class OwnedReference { public int Id { get; set; } - public string OwnedStringValue1 { get; set; } - public string OwnedStringValue2 { get; set; } - public string OwnedStringValue3 { get; set; } - public string OwnedStringValue4 { get; set; } + public string? OwnedStringValue1 { get; set; } + public string? OwnedStringValue2 { get; set; } + public string? OwnedStringValue3 { get; set; } + public string? OwnedStringValue4 { get; set; } public int OwnedIntValue1 { get; set; } public int OwnedIntValue2 { get; set; } public int OwnedIntValue3 { get; set; } public int OwnedIntValue4 { get; set; } [NotMapped] - public OwnedNestedReference OwnedNestedReference { get; set; } + public OwnedNestedReference? OwnedNestedReference { get; set; } } public class OwnedCollection @@ -63,10 +61,10 @@ public class OwnedCollection [DatabaseGenerated(DatabaseGeneratedOption.None)] public int Id { get; set; } - public string OwnedStringValue1 { get; set; } - public string OwnedStringValue2 { get; set; } - public string OwnedStringValue3 { get; set; } - public string OwnedStringValue4 { get; set; } + public string? OwnedStringValue1 { get; set; } + public string? OwnedStringValue2 { get; set; } + public string? OwnedStringValue3 { get; set; } + public string? OwnedStringValue4 { get; set; } public int OwnedIntValue1 { get; set; } public int OwnedIntValue2 { get; set; } public int OwnedIntValue3 { get; set; } @@ -76,10 +74,10 @@ public class OwnedCollection public class OwnedNestedReference { public int Id { get; set; } - public string OwnedNestedStringValue1 { get; set; } - public string OwnedNestedStringValue2 { get; set; } - public string OwnedNestedStringValue3 { get; set; } - public string OwnedNestedStringValue4 { get; set; } + public string? OwnedNestedStringValue1 { get; set; } + public string? OwnedNestedStringValue2 { get; set; } + public string? OwnedNestedStringValue3 { get; set; } + public string? OwnedNestedStringValue4 { get; set; } public int OwnedNestedIntValue1 { get; set; } public int OwnedNestedIntValue2 { get; set; } public int OwnedNestedIntValue3 { get; set; } @@ -92,7 +90,7 @@ public class BaseEntity public int BaseValue { get; set; } [NotMapped] - public OwnedReference OwnedReference { get; set; } + public OwnedReference? OwnedReference { get; set; } [NotMapped] public List OwnedCollection { get; set; } = []; diff --git a/test/EFCore.Relational.Specification.Tests/TestModels/Northwind/CustomerOrderHistory.cs b/test/EFCore.Relational.Specification.Tests/TestModels/Northwind/CustomerOrderHistory.cs index 69e4678e517..3567a1e72c7 100644 --- a/test/EFCore.Relational.Specification.Tests/TestModels/Northwind/CustomerOrderHistory.cs +++ b/test/EFCore.Relational.Specification.Tests/TestModels/Northwind/CustomerOrderHistory.cs @@ -3,11 +3,9 @@ namespace Microsoft.EntityFrameworkCore.TestModels.Northwind; -#nullable disable - public class CustomerOrderHistory { - public string ProductName { get; set; } + public string? ProductName { get; set; } public int Total { get; set; } } diff --git a/test/EFCore.Relational.Specification.Tests/TestModels/Northwind/MostExpensiveProduct.cs b/test/EFCore.Relational.Specification.Tests/TestModels/Northwind/MostExpensiveProduct.cs index 29a5069a328..278da04eae4 100644 --- a/test/EFCore.Relational.Specification.Tests/TestModels/Northwind/MostExpensiveProduct.cs +++ b/test/EFCore.Relational.Specification.Tests/TestModels/Northwind/MostExpensiveProduct.cs @@ -3,11 +3,9 @@ namespace Microsoft.EntityFrameworkCore.TestModels.Northwind; -#nullable disable - public class MostExpensiveProduct { - public string TenMostExpensiveProducts { get; set; } + public string? TenMostExpensiveProducts { get; set; } public decimal? UnitPrice { get; set; } } diff --git a/test/EFCore.Relational.Specification.Tests/TestModels/Northwind/NorthwindRelationalContext.cs b/test/EFCore.Relational.Specification.Tests/TestModels/Northwind/NorthwindRelationalContext.cs index d2f0504d34e..1bd6eec76e2 100644 --- a/test/EFCore.Relational.Specification.Tests/TestModels/Northwind/NorthwindRelationalContext.cs +++ b/test/EFCore.Relational.Specification.Tests/TestModels/Northwind/NorthwindRelationalContext.cs @@ -3,8 +3,6 @@ namespace Microsoft.EntityFrameworkCore.TestModels.Northwind; -#nullable disable - public abstract class NorthwindRelationalContext(DbContextOptions options) : NorthwindContext(options) { protected override void OnModelCreating(ModelBuilder modelBuilder) diff --git a/test/EFCore.Relational.Specification.Tests/TestModels/Operators/OperatorEntityDateTimeOffset.cs b/test/EFCore.Relational.Specification.Tests/TestModels/Operators/OperatorEntityDateTimeOffset.cs index 6b137793fa8..97f2871e73d 100644 --- a/test/EFCore.Relational.Specification.Tests/TestModels/Operators/OperatorEntityDateTimeOffset.cs +++ b/test/EFCore.Relational.Specification.Tests/TestModels/Operators/OperatorEntityDateTimeOffset.cs @@ -3,8 +3,6 @@ namespace Microsoft.EntityFrameworkCore.TestModels.Operators; -#nullable disable - public class OperatorEntityDateTimeOffset : OperatorEntityBase { public DateTimeOffset Value { get; set; } diff --git a/test/EFCore.Relational.Specification.Tests/TestModels/Operators/OperatorEntityNullableDateTimeOffset.cs b/test/EFCore.Relational.Specification.Tests/TestModels/Operators/OperatorEntityNullableDateTimeOffset.cs index 19cb8b2679e..9a433d74c3e 100644 --- a/test/EFCore.Relational.Specification.Tests/TestModels/Operators/OperatorEntityNullableDateTimeOffset.cs +++ b/test/EFCore.Relational.Specification.Tests/TestModels/Operators/OperatorEntityNullableDateTimeOffset.cs @@ -3,8 +3,6 @@ namespace Microsoft.EntityFrameworkCore.TestModels.Operators; -#nullable disable - public class OperatorEntityNullableDateTimeOffset : OperatorEntityBase { public DateTimeOffset? Value { get; set; } diff --git a/test/EFCore.Relational.Specification.Tests/TestModels/Operators/OperatorEntityString.cs b/test/EFCore.Relational.Specification.Tests/TestModels/Operators/OperatorEntityString.cs index cf5a8dc47dd..1b9b27ddd74 100644 --- a/test/EFCore.Relational.Specification.Tests/TestModels/Operators/OperatorEntityString.cs +++ b/test/EFCore.Relational.Specification.Tests/TestModels/Operators/OperatorEntityString.cs @@ -3,9 +3,7 @@ namespace Microsoft.EntityFrameworkCore.TestModels.Operators; -#nullable disable - public class OperatorEntityString : OperatorEntityBase { - public string Value { get; set; } + public string? Value { get; set; } } diff --git a/test/EFCore.Relational.Specification.Tests/TestModels/Operators/OperatorsContext.cs b/test/EFCore.Relational.Specification.Tests/TestModels/Operators/OperatorsContext.cs index 3e6f248ec98..604386a41d7 100644 --- a/test/EFCore.Relational.Specification.Tests/TestModels/Operators/OperatorsContext.cs +++ b/test/EFCore.Relational.Specification.Tests/TestModels/Operators/OperatorsContext.cs @@ -3,8 +3,6 @@ namespace Microsoft.EntityFrameworkCore.TestModels.Operators; -#nullable disable - public class OperatorsContext(DbContextOptions options) : DbContext(options) { protected override void OnModelCreating(ModelBuilder modelBuilder) diff --git a/test/EFCore.Relational.Specification.Tests/TestModels/Operators/OperatorsData.cs b/test/EFCore.Relational.Specification.Tests/TestModels/Operators/OperatorsData.cs index b051f6bee96..95dbf5657b1 100644 --- a/test/EFCore.Relational.Specification.Tests/TestModels/Operators/OperatorsData.cs +++ b/test/EFCore.Relational.Specification.Tests/TestModels/Operators/OperatorsData.cs @@ -3,8 +3,6 @@ namespace Microsoft.EntityFrameworkCore.TestModels.Operators; -#nullable disable - public class OperatorsData : ISetSource { public static readonly OperatorsData Instance = new(); diff --git a/test/EFCore.Relational.Specification.Tests/TestModels/OptionalDependent/OptionalDependentContext.cs b/test/EFCore.Relational.Specification.Tests/TestModels/OptionalDependent/OptionalDependentContext.cs index 0894d3ef780..7eac8b27c46 100644 --- a/test/EFCore.Relational.Specification.Tests/TestModels/OptionalDependent/OptionalDependentContext.cs +++ b/test/EFCore.Relational.Specification.Tests/TestModels/OptionalDependent/OptionalDependentContext.cs @@ -3,12 +3,10 @@ namespace Microsoft.EntityFrameworkCore.TestModels.OptionalDependent; -#nullable disable - public class OptionalDependentContext(DbContextOptions options) : DbContext(options) { - public DbSet EntitiesAllOptional { get; set; } - public DbSet EntitiesSomeRequired { get; set; } + public DbSet EntitiesAllOptional { get; set; } = null!; + public DbSet EntitiesSomeRequired { get; set; } = null!; public static async Task SeedAsync(OptionalDependentContext context) { diff --git a/test/EFCore.Relational.Specification.Tests/TestModels/OptionalDependent/OptionalDependentData.cs b/test/EFCore.Relational.Specification.Tests/TestModels/OptionalDependent/OptionalDependentData.cs index 680a40a9f8b..4857bee9840 100644 --- a/test/EFCore.Relational.Specification.Tests/TestModels/OptionalDependent/OptionalDependentData.cs +++ b/test/EFCore.Relational.Specification.Tests/TestModels/OptionalDependent/OptionalDependentData.cs @@ -6,8 +6,6 @@ namespace Microsoft.EntityFrameworkCore.TestModels.OptionalDependent; -#nullable disable - public class OptionalDependentData : ISetSource { public IReadOnlyList EntitiesAllOptional { get; } = CreateEntitiesAllOptional(); diff --git a/test/EFCore.Relational.Specification.Tests/TestModels/OptionalDependent/OptionalDependentEntityAllOptional.cs b/test/EFCore.Relational.Specification.Tests/TestModels/OptionalDependent/OptionalDependentEntityAllOptional.cs index 82c91f9f4e1..a17e19b76e7 100644 --- a/test/EFCore.Relational.Specification.Tests/TestModels/OptionalDependent/OptionalDependentEntityAllOptional.cs +++ b/test/EFCore.Relational.Specification.Tests/TestModels/OptionalDependent/OptionalDependentEntityAllOptional.cs @@ -3,12 +3,10 @@ namespace Microsoft.EntityFrameworkCore.TestModels.OptionalDependent; -#nullable disable - public class OptionalDependentEntityAllOptional { public int Id { get; set; } - public string Name { get; set; } + public string? Name { get; set; } - public OptionalDependentJsonAllOptional Json { get; set; } + public OptionalDependentJsonAllOptional? Json { get; set; } } diff --git a/test/EFCore.Relational.Specification.Tests/TestModels/OptionalDependent/OptionalDependentEntitySomeRequired.cs b/test/EFCore.Relational.Specification.Tests/TestModels/OptionalDependent/OptionalDependentEntitySomeRequired.cs index fd3b2c2e30e..c81e02041bd 100644 --- a/test/EFCore.Relational.Specification.Tests/TestModels/OptionalDependent/OptionalDependentEntitySomeRequired.cs +++ b/test/EFCore.Relational.Specification.Tests/TestModels/OptionalDependent/OptionalDependentEntitySomeRequired.cs @@ -3,12 +3,10 @@ namespace Microsoft.EntityFrameworkCore.TestModels.OptionalDependent; -#nullable disable - public class OptionalDependentEntitySomeRequired { public int Id { get; set; } - public string Name { get; set; } + public string? Name { get; set; } - public OptionalDependentJsonSomeRequired Json { get; set; } + public OptionalDependentJsonSomeRequired? Json { get; set; } } diff --git a/test/EFCore.Relational.Specification.Tests/TestModels/OptionalDependent/OptionalDependentJsonAllOptional.cs b/test/EFCore.Relational.Specification.Tests/TestModels/OptionalDependent/OptionalDependentJsonAllOptional.cs index 30e0f669ccf..bfcb5265510 100644 --- a/test/EFCore.Relational.Specification.Tests/TestModels/OptionalDependent/OptionalDependentJsonAllOptional.cs +++ b/test/EFCore.Relational.Specification.Tests/TestModels/OptionalDependent/OptionalDependentJsonAllOptional.cs @@ -3,13 +3,11 @@ namespace Microsoft.EntityFrameworkCore.TestModels.OptionalDependent; -#nullable disable - public class OptionalDependentJsonAllOptional { - public string OpProp1 { get; set; } + public string? OpProp1 { get; set; } public int? OpProp2 { get; set; } - public OptionalDependentNestedJsonAllOptional OpNav1 { get; set; } - public OptionalDependentNestedJsonSomeRequired OpNav2 { get; set; } + public OptionalDependentNestedJsonAllOptional? OpNav1 { get; set; } + public OptionalDependentNestedJsonSomeRequired? OpNav2 { get; set; } } diff --git a/test/EFCore.Relational.Specification.Tests/TestModels/OptionalDependent/OptionalDependentJsonSomeRequired.cs b/test/EFCore.Relational.Specification.Tests/TestModels/OptionalDependent/OptionalDependentJsonSomeRequired.cs index 55f87aaac15..ef28957972e 100644 --- a/test/EFCore.Relational.Specification.Tests/TestModels/OptionalDependent/OptionalDependentJsonSomeRequired.cs +++ b/test/EFCore.Relational.Specification.Tests/TestModels/OptionalDependent/OptionalDependentJsonSomeRequired.cs @@ -3,18 +3,16 @@ namespace Microsoft.EntityFrameworkCore.TestModels.OptionalDependent; -#nullable disable - public class OptionalDependentJsonSomeRequired { - public string OpProp1 { get; set; } + public string? OpProp1 { get; set; } public int? OpProp2 { get; set; } public double ReqProp { get; set; } - public OptionalDependentNestedJsonAllOptional OpNav1 { get; set; } - public OptionalDependentNestedJsonSomeRequired OpNav2 { get; set; } + public OptionalDependentNestedJsonAllOptional? OpNav1 { get; set; } + public OptionalDependentNestedJsonSomeRequired? OpNav2 { get; set; } - public OptionalDependentNestedJsonAllOptional ReqNav1 { get; set; } - public OptionalDependentNestedJsonSomeRequired ReqNav2 { get; set; } + public OptionalDependentNestedJsonAllOptional ReqNav1 { get; set; } = null!; + public OptionalDependentNestedJsonSomeRequired ReqNav2 { get; set; } = null!; } diff --git a/test/EFCore.Relational.Specification.Tests/TestModels/OptionalDependent/OptionalDependentNestedJsonAllOptional.cs b/test/EFCore.Relational.Specification.Tests/TestModels/OptionalDependent/OptionalDependentNestedJsonAllOptional.cs index 700a23ce6b5..a1a1a927731 100644 --- a/test/EFCore.Relational.Specification.Tests/TestModels/OptionalDependent/OptionalDependentNestedJsonAllOptional.cs +++ b/test/EFCore.Relational.Specification.Tests/TestModels/OptionalDependent/OptionalDependentNestedJsonAllOptional.cs @@ -3,10 +3,8 @@ namespace Microsoft.EntityFrameworkCore.TestModels.OptionalDependent; -#nullable disable - public class OptionalDependentNestedJsonAllOptional { - public string OpNested1 { get; set; } + public string? OpNested1 { get; set; } public int? OpNested2 { get; set; } } diff --git a/test/EFCore.Relational.Specification.Tests/TestModels/OptionalDependent/OptionalDependentNestedJsonSomeRequired.cs b/test/EFCore.Relational.Specification.Tests/TestModels/OptionalDependent/OptionalDependentNestedJsonSomeRequired.cs index f7361605f8c..d080ace312a 100644 --- a/test/EFCore.Relational.Specification.Tests/TestModels/OptionalDependent/OptionalDependentNestedJsonSomeRequired.cs +++ b/test/EFCore.Relational.Specification.Tests/TestModels/OptionalDependent/OptionalDependentNestedJsonSomeRequired.cs @@ -3,11 +3,9 @@ namespace Microsoft.EntityFrameworkCore.TestModels.OptionalDependent; -#nullable disable - public class OptionalDependentNestedJsonSomeRequired { - public string OpNested1 { get; set; } + public string? OpNested1 { get; set; } public int? OpNested2 { get; set; } public bool ReqNested1 { get; set; } diff --git a/test/EFCore.Relational.Specification.Tests/TestModels/StoreValueGenerationModel/StoreValueGenerationContext.cs b/test/EFCore.Relational.Specification.Tests/TestModels/StoreValueGenerationModel/StoreValueGenerationContext.cs index ead15a17d88..b7e1059070d 100644 --- a/test/EFCore.Relational.Specification.Tests/TestModels/StoreValueGenerationModel/StoreValueGenerationContext.cs +++ b/test/EFCore.Relational.Specification.Tests/TestModels/StoreValueGenerationModel/StoreValueGenerationContext.cs @@ -3,8 +3,6 @@ namespace Microsoft.EntityFrameworkCore.TestModels.StoreValueGenerationModel; -#nullable disable - public class StoreValueGenerationContext(DbContextOptions options) : PoolableDbContext(options) { public DbSet WithSomeDatabaseGenerated diff --git a/test/EFCore.Relational.Specification.Tests/TestUtilities/RelationalModelAsserter.cs b/test/EFCore.Relational.Specification.Tests/TestUtilities/RelationalModelAsserter.cs index f634372fa4f..289747fa836 100644 --- a/test/EFCore.Relational.Specification.Tests/TestUtilities/RelationalModelAsserter.cs +++ b/test/EFCore.Relational.Specification.Tests/TestUtilities/RelationalModelAsserter.cs @@ -5,8 +5,6 @@ namespace Microsoft.EntityFrameworkCore.TestUtilities; -#nullable disable - public class RelationalModelAsserter : ModelAsserter { public static new RelationalModelAsserter Instance { get; } = new(); @@ -60,10 +58,10 @@ public override void AssertEqual( compareMemberAnnotations)), () => { - var expectedRelationalModel = (IRelationalModel)((IModel)expected) - ?.FindRuntimeAnnotationValue(RelationalAnnotationNames.RelationalModel); - var actualRelationalModel = (IRelationalModel)((IModel)actual) - ?.FindRuntimeAnnotationValue(RelationalAnnotationNames.RelationalModel); + var expectedRelationalModel = (IRelationalModel)((IModel)expected)? + .FindRuntimeAnnotationValue(RelationalAnnotationNames.RelationalModel)!; + var actualRelationalModel = (IRelationalModel)((IModel)actual)? + .FindRuntimeAnnotationValue(RelationalAnnotationNames.RelationalModel)!; if (expectedRelationalModel != null) { AssertEqual(expectedRelationalModel, actualRelationalModel, compareMemberAnnotations); @@ -182,8 +180,8 @@ public virtual bool AssertEqual( } public override bool AssertEqual( - IReadOnlyEntityType expected, - IReadOnlyEntityType actual, + IReadOnlyEntityType? expected, + IReadOnlyEntityType? actual, IEnumerable expectedAnnotations, IEnumerable actualAnnotations, bool compareBackreferences = false, @@ -410,8 +408,8 @@ public virtual bool AssertEqual( } public virtual bool AssertEqual( - IReadOnlyStoredProcedure expected, - IReadOnlyStoredProcedure actual, + IReadOnlyStoredProcedure? expected, + IReadOnlyStoredProcedure? actual, bool compareBackreferences = false, bool compareAnnotations = false) { @@ -421,6 +419,8 @@ public virtual bool AssertEqual( return true; } + Assert.NotNull(actual); + var expectedAnnotations = compareAnnotations ? expected.GetAnnotations() : []; var actualAnnotations = compareAnnotations ? actual.GetAnnotations() : []; @@ -719,8 +719,8 @@ public override bool AssertEqual( } public override bool AssertEqual( - IReadOnlyProperty expected, - IReadOnlyProperty actual, + IReadOnlyProperty? expected, + IReadOnlyProperty? actual, IEnumerable expectedAnnotations, IEnumerable actualAnnotations, bool compareBackreferences = false, @@ -1482,10 +1482,10 @@ public virtual bool AssertEqual( { AssertEqualBase( expected.ReturnValue, - actual.ReturnValue, + actual.ReturnValue!, compareMemberAnnotations ? expected.GetAnnotations() : [], compareMemberAnnotations ? actual.GetAnnotations() : []); - Assert.Same(actual, actual.ReturnValue.StoredProcedure); + Assert.Same(actual, actual.ReturnValue!.StoredProcedure); Assert.Equal( expected.ReturnValue.PropertyMappings.Select(x => x), actual.ReturnValue.PropertyMappings, (expected, actual) => @@ -1668,8 +1668,8 @@ public virtual bool AssertEqual( } public virtual bool AssertEqual( - IStoredProcedureMapping expected, - IStoredProcedureMapping actual, + IStoredProcedureMapping? expected, + IStoredProcedureMapping? actual, bool compareMemberAnnotations) { if (expected == null) @@ -1678,6 +1678,8 @@ public virtual bool AssertEqual( return true; } + Assert.NotNull(actual); + return AssertEqual( expected, actual, @@ -1696,7 +1698,7 @@ public virtual bool AssertEqual( Assert.Multiple( () => AssertEqualBase(expected, actual, expectedAnnotations, actualAnnotations), () => Assert.Equal(expected.StoredProcedure.GetSchemaQualifiedName(), actual.StoredProcedure.GetSchemaQualifiedName()), - () => Assert.Contains(expected.TableMapping?.Table.SchemaQualifiedName, actual.TableMapping?.Table.SchemaQualifiedName), + () => Assert.Contains(expected.TableMapping?.Table.SchemaQualifiedName!, actual.TableMapping?.Table.SchemaQualifiedName), () => Assert.Equal( expected.ResultColumnMappings.Select(x => x), actual.ResultColumnMappings, (expected, actual) => diff --git a/test/EFCore.Relational.Specification.Tests/TransactionInterceptionTestBase.cs b/test/EFCore.Relational.Specification.Tests/TransactionInterceptionTestBase.cs index b32f9e1a3f9..d169d1fac73 100644 --- a/test/EFCore.Relational.Specification.Tests/TransactionInterceptionTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/TransactionInterceptionTestBase.cs @@ -5,8 +5,6 @@ namespace Microsoft.EntityFrameworkCore; -#nullable disable - public abstract class TransactionInterceptionTestBase(InterceptionTestBase.InterceptionFixtureBase fixture) : InterceptionTestBase(fixture) { [Theory, InlineData(false), InlineData(true)] @@ -35,8 +33,8 @@ public virtual async Task UseTransaction_without_interceptor(bool async) : context.Database.UseTransaction(transaction); { - Assert.NotNull(contextTransaction.GetDbTransaction()); - Assert.Same(transaction, contextTransaction.GetDbTransaction()); + Assert.NotNull(contextTransaction!.GetDbTransaction()); + Assert.Same(transaction, contextTransaction!.GetDbTransaction()); } AssertUseTransactionEvents(listener); @@ -199,7 +197,7 @@ public virtual async Task Intercept_UseTransaction(bool async) ? await context.Database.UseTransactionAsync(transaction) : context.Database.UseTransaction(transaction); - AssertUseTransaction(context, contextTransaction, interceptor, async); + AssertUseTransaction(context, contextTransaction!, interceptor, async); } AssertUseTransactionEvents(listener); @@ -218,9 +216,9 @@ public virtual async Task Intercept_UseTransaction_to_wrap(bool async) ? await context.Database.UseTransactionAsync(transaction) : context.Database.UseTransaction(transaction); - Assert.IsType(contextTransaction.GetDbTransaction()); + Assert.IsType(contextTransaction!.GetDbTransaction()); - AssertUseTransaction(context, contextTransaction, interceptor, async); + AssertUseTransaction(context, contextTransaction!, interceptor, async); AssertUseTransactionEvents(listener); } @@ -569,7 +567,7 @@ public override void Commit() public override void Rollback() => _transaction.Rollback(); - protected override DbConnection DbConnection + protected override DbConnection? DbConnection => _transaction.Connection; public override IsolationLevel IsolationLevel @@ -794,41 +792,41 @@ private static void AssertError( private static void AssertBeginTransactionEvents(ITestDiagnosticListener listener) => listener.AssertEventsInOrder( - RelationalEventId.TransactionStarting.Name, - RelationalEventId.TransactionStarted.Name); + RelationalEventId.TransactionStarting.Name!, + RelationalEventId.TransactionStarted.Name!); private static void AssertUseTransactionEvents(ITestDiagnosticListener listener) - => listener.AssertEventsInOrder(RelationalEventId.TransactionUsed.Name); + => listener.AssertEventsInOrder(RelationalEventId.TransactionUsed.Name!); private static void AssertCommitEvents(ITestDiagnosticListener listener) => listener.AssertEventsInOrder( - RelationalEventId.TransactionCommitting.Name, - RelationalEventId.TransactionCommitted.Name); + RelationalEventId.TransactionCommitting.Name!, + RelationalEventId.TransactionCommitted.Name!); private static void AssertRollBackEvents(ITestDiagnosticListener listener) => listener.AssertEventsInOrder( - RelationalEventId.TransactionRollingBack.Name, - RelationalEventId.TransactionRolledBack.Name); + RelationalEventId.TransactionRollingBack.Name!, + RelationalEventId.TransactionRolledBack.Name!); private static void AssertCreateSavepointEvents(ITestDiagnosticListener listener) => listener.AssertEventsInOrder( - RelationalEventId.CreatingTransactionSavepoint.Name, - RelationalEventId.CreatedTransactionSavepoint.Name); + RelationalEventId.CreatingTransactionSavepoint.Name!, + RelationalEventId.CreatedTransactionSavepoint.Name!); private static void AssertRollbackToSavepointEvents(ITestDiagnosticListener listener) => listener.AssertEventsInOrder( - RelationalEventId.RollingBackToTransactionSavepoint.Name, - RelationalEventId.RolledBackToTransactionSavepoint.Name); + RelationalEventId.RollingBackToTransactionSavepoint.Name!, + RelationalEventId.RolledBackToTransactionSavepoint.Name!); private static void AssertReleaseSavepointEvents(ITestDiagnosticListener listener) => listener.AssertEventsInOrder( - RelationalEventId.ReleasingTransactionSavepoint.Name, - RelationalEventId.ReleasedTransactionSavepoint.Name); + RelationalEventId.ReleasingTransactionSavepoint.Name!, + RelationalEventId.ReleasedTransactionSavepoint.Name!); protected class TransactionInterceptor : IDbTransactionInterceptor { - public DbContext Context { get; set; } - public Exception Exception { get; set; } + public DbContext? Context { get; set; } + public Exception? Exception { get; set; } public Guid TransactionId { get; set; } public Guid ConnectionId { get; set; } public IsolationLevel IsolationLevel { get; set; } diff --git a/test/EFCore.Relational.Specification.Tests/TransactionTestBase.cs b/test/EFCore.Relational.Specification.Tests/TransactionTestBase.cs index e668a61dedb..67bc5a31bdb 100644 --- a/test/EFCore.Relational.Specification.Tests/TransactionTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/TransactionTestBase.cs @@ -10,8 +10,6 @@ // ReSharper disable InconsistentNaming namespace Microsoft.EntityFrameworkCore; -#nullable disable - public abstract class TransactionTestBase(TFixture fixture) : IClassFixture, IAsyncLifetime where TFixture : TransactionTestBase.TransactionFixtureBase, new() { @@ -336,7 +334,7 @@ public virtual async Task SaveChanges_uses_ambient_transaction_with_connectionSt return; } - DbConnection connection = null; + DbConnection? connection = null; await RetryOnDistributedTransactionNotSupportedAsync(async () => { @@ -383,7 +381,7 @@ await context.AddAsync( } }); - Assert.Equal(ConnectionState.Closed, connection.State); + Assert.Equal(ConnectionState.Closed, connection!.State); AssertStoreInitialState(); } @@ -1500,9 +1498,9 @@ protected override Task SeedAsync(PoolableDbContext context) protected abstract class TransactionEntity { public int Id { get; set; } - public string Name { get; set; } + public string? Name { get; set; } - public override bool Equals(object obj) + public override bool Equals(object? obj) => obj is TransactionCustomer otherCustomer && Id == otherCustomer.Id && Name == otherCustomer.Name; public override string ToString() diff --git a/test/EFCore.Relational.Specification.Tests/TwoDatabasesTestBase.cs b/test/EFCore.Relational.Specification.Tests/TwoDatabasesTestBase.cs index 16f901f4b1b..6e9c43f301f 100644 --- a/test/EFCore.Relational.Specification.Tests/TwoDatabasesTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/TwoDatabasesTestBase.cs @@ -5,8 +5,6 @@ namespace Microsoft.EntityFrameworkCore; -#nullable disable - public abstract class TwoDatabasesTestBase(FixtureBase fixture) { protected FixtureBase Fixture { get; } = fixture; @@ -83,7 +81,7 @@ public virtual void Can_set_connection_string_in_interceptor(bool withConnection CreateTestOptions(new DbContextOptionsBuilder(), withConnectionString) .AddInterceptors( new ConnectionStringConnectionInterceptor( - connectionString1, withConnectionString ? DummyConnectionString : "")) + connectionString1!, withConnectionString ? DummyConnectionString : "")) .Options)) { var data = context.Foos.ToList(); @@ -107,7 +105,7 @@ public override InterceptionResult ConnectionOpening( ConnectionEventData eventData, InterceptionResult result) { - Assert.Equal(_dummyConnectionString, eventData.Context.Database.GetConnectionString()); + Assert.Equal(_dummyConnectionString, eventData.Context!.Database.GetConnectionString()); eventData.Context.Database.SetConnectionString(_goodConnectionString); return result; @@ -115,7 +113,7 @@ public override InterceptionResult ConnectionOpening( public override void ConnectionClosed(DbConnection connection, ConnectionEndEventData eventData) { - Assert.Equal(_goodConnectionString, eventData.Context.Database.GetConnectionString()); + Assert.Equal(_goodConnectionString, eventData.Context!.Database.GetConnectionString()); eventData.Context.Database.SetConnectionString(_dummyConnectionString); } } @@ -157,6 +155,6 @@ protected class Foo [DatabaseGenerated(DatabaseGeneratedOption.None)] public int Id { get; set; } - public string Bar { get; set; } + public string? Bar { get; set; } } } diff --git a/test/EFCore.Relational.Specification.Tests/Update/JsonUpdateFixtureBase.cs b/test/EFCore.Relational.Specification.Tests/Update/JsonUpdateFixtureBase.cs index c127133daf6..01e4353556c 100644 --- a/test/EFCore.Relational.Specification.Tests/Update/JsonUpdateFixtureBase.cs +++ b/test/EFCore.Relational.Specification.Tests/Update/JsonUpdateFixtureBase.cs @@ -8,8 +8,6 @@ namespace Microsoft.EntityFrameworkCore.Update; -#nullable disable - public abstract class JsonUpdateFixtureBase : SharedStoreFixtureBase { protected override string StoreName @@ -24,9 +22,11 @@ public override DbContextOptionsBuilder AddOptions(DbContextOptionsBuilder build protected override void OnModelCreating(ModelBuilder modelBuilder, DbContext context) { modelBuilder.Entity().Property(x => x.Id).ValueGeneratedNever(); + modelBuilder.Entity().Property(x => x.Name).IsRequired(false); modelBuilder.Entity().OwnsOne( x => x.OwnedReferenceRoot, b => { + b.Property(x => x.Name).IsRequired(false); b.ToJson(); b.WithOwner(x => x.Owner); b.OwnsOne( @@ -51,6 +51,7 @@ protected override void OnModelCreating(ModelBuilder modelBuilder, DbContext con modelBuilder.Entity().OwnsMany( x => x.OwnedCollectionRoot, b => { + b.Property(x => x.Name).IsRequired(false); b.OwnsOne( x => x.OwnedReferenceBranch, bb => { @@ -72,6 +73,7 @@ protected override void OnModelCreating(ModelBuilder modelBuilder, DbContext con modelBuilder.Entity().Property(x => x.Id).ValueGeneratedNever(); modelBuilder.Entity(b => { + b.Property(x => x.Name).IsRequired(false); b.OwnsOne( x => x.ReferenceOnBase, bb => { @@ -116,7 +118,29 @@ protected override void OnModelCreating(ModelBuilder modelBuilder, DbContext con modelBuilder.Ignore(); modelBuilder.Ignore(); - modelBuilder.Entity().Property(x => x.Id).ValueGeneratedNever(); + modelBuilder.Entity(b => + { + b.Property(x => x.Id).ValueGeneratedNever(); + b.Property(x => x.TestBooleanCollection).IsRequired(false); + b.Property(x => x.TestCharacterCollection).IsRequired(false); + b.Property(x => x.TestDateTimeCollection).IsRequired(false); + b.Property(x => x.TestDateTimeOffsetCollection).IsRequired(false); + b.Property(x => x.TestDecimalCollection).IsRequired(false); + b.Property(x => x.TestDefaultStringCollection).IsRequired(false); + b.Property(x => x.TestDoubleCollection).IsRequired(false); + b.Property(x => x.TestEnumCollection).IsRequired(false); + b.Property(x => x.TestEnumWithIntConverterCollection).IsRequired(false); + b.Property(x => x.TestInt16Collection).IsRequired(false); + b.Property(x => x.TestInt32Collection).IsRequired(false); + b.Property(x => x.TestInt64Collection).IsRequired(false); + b.Property(x => x.TestMaxLengthStringCollection).IsRequired(false); + b.Property(x => x.TestSignedByteCollection).IsRequired(false); + b.Property(x => x.TestSingleCollection).IsRequired(false); + b.Property(x => x.TestTimeSpanCollection).IsRequired(false); + b.Property(x => x.TestUnsignedInt16Collection).IsRequired(false); + b.Property(x => x.TestUnsignedInt32Collection).IsRequired(false); + b.Property(x => x.TestUnsignedInt64Collection).IsRequired(false); + }); modelBuilder.Entity().OwnsOne( x => x.Reference, b => { diff --git a/test/EFCore.Relational.Specification.Tests/Update/JsonUpdateTestBase.cs b/test/EFCore.Relational.Specification.Tests/Update/JsonUpdateTestBase.cs index 84e12ec86a2..9576e7841ef 100644 --- a/test/EFCore.Relational.Specification.Tests/Update/JsonUpdateTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/Update/JsonUpdateTestBase.cs @@ -6,8 +6,6 @@ namespace Microsoft.EntityFrameworkCore.Update; -#nullable disable - public abstract class JsonUpdateTestBase(TFixture fixture) : IClassFixture where TFixture : JsonUpdateFixtureBase, new() { @@ -63,7 +61,7 @@ public virtual Task Add_entity_with_json() Assert.Equal("RootName", newEntity.OwnedReferenceRoot.Name); Assert.Equal(42, newEntity.OwnedReferenceRoot.Number); Assert.Empty(newEntity.OwnedReferenceRoot.OwnedCollectionBranch); - Assert.Equal(new DateTime(2010, 10, 10), newEntity.OwnedReferenceRoot.OwnedReferenceBranch.Date); + Assert.Equal(new DateTime(2010, 10, 10), newEntity.OwnedReferenceRoot.OwnedReferenceBranch!.Date); Assert.Equal(JsonEnum.Three, newEntity.OwnedReferenceRoot.OwnedReferenceBranch.Enum); Assert.Equal(42.42m, newEntity.OwnedReferenceRoot.OwnedReferenceBranch.Fraction); Assert.Equal(7, newEntity.OwnedReferenceRoot.OwnedReferenceBranch.Id); @@ -88,7 +86,7 @@ public virtual Task Add_entity_with_json_null_navigations() { Id = 2, Name = "NewEntity", - OwnedCollectionRoot = null, + OwnedCollectionRoot = null!, OwnedReferenceRoot = new JsonOwnedRoot { Name = "RootName", @@ -104,7 +102,7 @@ public virtual Task Add_entity_with_json_null_navigations() [ new JsonOwnedLeaf { SomethingSomething = "ss1" }, new JsonOwnedLeaf { SomethingSomething = "ss2" } ], - OwnedReferenceLeaf = null, + OwnedReferenceLeaf = null!, } }, }; @@ -124,7 +122,7 @@ public virtual Task Add_entity_with_json_null_navigations() Assert.Equal("RootName", newEntity.OwnedReferenceRoot.Name); Assert.Equal(42, newEntity.OwnedReferenceRoot.Number); Assert.Null(newEntity.OwnedReferenceRoot.OwnedCollectionBranch); - Assert.Equal(new DateTime(2010, 10, 10), newEntity.OwnedReferenceRoot.OwnedReferenceBranch.Date); + Assert.Equal(new DateTime(2010, 10, 10), newEntity.OwnedReferenceRoot.OwnedReferenceBranch!.Date); Assert.Equal(JsonEnum.Three, newEntity.OwnedReferenceRoot.OwnedReferenceBranch.Enum); Assert.Equal(42.42m, newEntity.OwnedReferenceRoot.OwnedReferenceBranch.Fraction); Assert.Equal(7, newEntity.OwnedReferenceRoot.OwnedReferenceBranch.Id); @@ -147,7 +145,7 @@ public virtual Task Add_json_reference_root() { var query = await context.JsonEntitiesBasic.ToListAsync(); var entity = query.Single(); - entity.OwnedReferenceRoot = null; + entity.OwnedReferenceRoot = null!; await context.SaveChangesAsync(); }, async context => @@ -184,7 +182,7 @@ public virtual Task Add_json_reference_root() Assert.Equal("RootName", updatedReference.Name); Assert.Equal(42, updatedReference.Number); Assert.Empty(updatedReference.OwnedCollectionBranch); - Assert.Equal(new DateTime(2010, 10, 10), updatedReference.OwnedReferenceBranch.Date); + Assert.Equal(new DateTime(2010, 10, 10), updatedReference.OwnedReferenceBranch!.Date); Assert.Equal(JsonEnum.Three, updatedReference.OwnedReferenceBranch.Enum); Assert.Equal(42.42m, updatedReference.OwnedReferenceBranch.Fraction); Assert.Equal(7, updatedReference.OwnedReferenceBranch.Id); @@ -204,7 +202,7 @@ public virtual Task Add_json_reference_leaf() { var query = await context.JsonEntitiesBasic.ToListAsync(); var entity = query.Single(); - entity.OwnedReferenceRoot.OwnedCollectionBranch[0].OwnedReferenceLeaf = null; + entity.OwnedReferenceRoot.OwnedCollectionBranch[0].OwnedReferenceLeaf = null!; await context.SaveChangesAsync(); }, async context => @@ -267,12 +265,12 @@ public virtual Task Add_element_to_json_collection_root() Assert.Equal("new Name", updatedCollection[2].Name); Assert.Equal(142, updatedCollection[2].Number); Assert.Empty(updatedCollection[2].OwnedCollectionBranch); - Assert.Equal(new DateTime(2010, 10, 10), updatedCollection[2].OwnedReferenceBranch.Date); - Assert.Equal(JsonEnum.Three, updatedCollection[2].OwnedReferenceBranch.Enum); - Assert.Equal(7, updatedCollection[2].OwnedReferenceBranch.Id); - Assert.Equal(42.42m, updatedCollection[2].OwnedReferenceBranch.Fraction); - Assert.Equal("ss3", updatedCollection[2].OwnedReferenceBranch.OwnedReferenceLeaf.SomethingSomething); - var collectionLeaf = updatedCollection[2].OwnedReferenceBranch.OwnedCollectionLeaf; + Assert.Equal(new DateTime(2010, 10, 10), updatedCollection[2].OwnedReferenceBranch!.Date); + Assert.Equal(JsonEnum.Three, updatedCollection[2].OwnedReferenceBranch!.Enum); + Assert.Equal(7, updatedCollection[2].OwnedReferenceBranch!.Id); + Assert.Equal(42.42m, updatedCollection[2].OwnedReferenceBranch!.Fraction); + Assert.Equal("ss3", updatedCollection[2].OwnedReferenceBranch!.OwnedReferenceLeaf.SomethingSomething); + var collectionLeaf = updatedCollection[2].OwnedReferenceBranch!.OwnedCollectionLeaf; Assert.Equal(2, collectionLeaf.Count); Assert.Equal("ss1", collectionLeaf[0].SomethingSomething); Assert.Equal("ss2", collectionLeaf[1].SomethingSomething); @@ -292,14 +290,14 @@ public virtual Task Add_element_to_json_collection_root_null_navigations() { Name = "new Name", Number = 142, - OwnedCollectionBranch = null, + OwnedCollectionBranch = null!, OwnedReferenceBranch = new JsonOwnedBranch { Id = 7, Date = new DateTime(2010, 10, 10), Enum = JsonEnum.Three, Fraction = 42.42m, - OwnedReferenceLeaf = null + OwnedReferenceLeaf = null! } }; @@ -315,12 +313,12 @@ public virtual Task Add_element_to_json_collection_root_null_navigations() Assert.Equal("new Name", updatedCollection[2].Name); Assert.Equal(142, updatedCollection[2].Number); Assert.Null(updatedCollection[2].OwnedCollectionBranch); - Assert.Equal(new DateTime(2010, 10, 10), updatedCollection[2].OwnedReferenceBranch.Date); - Assert.Equal(JsonEnum.Three, updatedCollection[2].OwnedReferenceBranch.Enum); - Assert.Equal(7, updatedCollection[2].OwnedReferenceBranch.Id); - Assert.Equal(42.42m, updatedCollection[2].OwnedReferenceBranch.Fraction); - Assert.Null(updatedCollection[2].OwnedReferenceBranch.OwnedReferenceLeaf); - Assert.Null(updatedCollection[2].OwnedReferenceBranch.OwnedCollectionLeaf); + Assert.Equal(new DateTime(2010, 10, 10), updatedCollection[2].OwnedReferenceBranch!.Date); + Assert.Equal(JsonEnum.Three, updatedCollection[2].OwnedReferenceBranch!.Enum); + Assert.Equal(7, updatedCollection[2].OwnedReferenceBranch!.Id); + Assert.Equal(42.42m, updatedCollection[2].OwnedReferenceBranch!.Fraction); + Assert.Null(updatedCollection[2].OwnedReferenceBranch!.OwnedReferenceLeaf); + Assert.Null(updatedCollection[2].OwnedReferenceBranch!.OwnedCollectionLeaf); }); [Fact] @@ -375,7 +373,7 @@ public virtual Task Add_element_to_json_collection_leaf() var query = await context.JsonEntitiesBasic.ToListAsync(); var entity = query.Single(); var newLeaf = new JsonOwnedLeaf { SomethingSomething = "ss1" }; - entity.OwnedReferenceRoot.OwnedReferenceBranch.OwnedCollectionLeaf.Add(newLeaf); + entity.OwnedReferenceRoot.OwnedReferenceBranch!.OwnedCollectionLeaf.Add(newLeaf); ClearLog(); await context.SaveChangesAsync(); @@ -385,7 +383,7 @@ public virtual Task Add_element_to_json_collection_leaf() async context => { var updatedEntity = await context.JsonEntitiesBasic.SingleAsync(); - var updatedCollection = updatedEntity.OwnedReferenceRoot.OwnedReferenceBranch.OwnedCollectionLeaf; + var updatedCollection = updatedEntity.OwnedReferenceRoot.OwnedReferenceBranch!.OwnedCollectionLeaf; Assert.Equal(3, updatedCollection.Count); Assert.Equal("ss1", updatedCollection[2].SomethingSomething); }); @@ -420,7 +418,7 @@ public virtual Task Delete_json_reference_root() { var query = await context.JsonEntitiesBasic.ToListAsync(); var entity = query.Single(); - entity.OwnedReferenceRoot = null; + entity.OwnedReferenceRoot = null!; ClearLog(); await context.SaveChangesAsync(); }, @@ -439,14 +437,14 @@ public virtual Task Delete_json_reference_leaf() { var query = await context.JsonEntitiesBasic.ToListAsync(); var entity = query.Single(); - entity.OwnedReferenceRoot.OwnedReferenceBranch.OwnedReferenceLeaf = null; + entity.OwnedReferenceRoot.OwnedReferenceBranch!.OwnedReferenceLeaf = null!; ClearLog(); await context.SaveChangesAsync(); }, async context => { var updatedEntity = await context.JsonEntitiesBasic.SingleAsync(); - Assert.Null(updatedEntity.OwnedReferenceRoot.OwnedReferenceBranch.OwnedReferenceLeaf); + Assert.Null(updatedEntity.OwnedReferenceRoot.OwnedReferenceBranch!.OwnedReferenceLeaf); }); [Fact] @@ -458,7 +456,7 @@ public virtual Task Delete_json_collection_root() { var query = await context.JsonEntitiesBasic.ToListAsync(); var entity = query.Single(); - entity.OwnedCollectionRoot = null; + entity.OwnedCollectionRoot = null!; ClearLog(); await context.SaveChangesAsync(); }, @@ -477,7 +475,7 @@ public virtual Task Delete_json_collection_branch() { var query = await context.JsonEntitiesBasic.ToListAsync(); var entity = query.Single(); - entity.OwnedReferenceRoot.OwnedCollectionBranch = null; + entity.OwnedReferenceRoot.OwnedCollectionBranch = null!; ClearLog(); await context.SaveChangesAsync(); }, @@ -600,7 +598,7 @@ public virtual Task Edit_element_in_json_multiple_levels_partial_update() { var query = await context.JsonEntitiesBasic.ToListAsync(); var entity = query.Single(); - entity.OwnedReferenceRoot.OwnedReferenceBranch.Date = new DateTime(2111, 11, 11); + entity.OwnedReferenceRoot.OwnedReferenceBranch!.Date = new DateTime(2111, 11, 11); entity.OwnedReferenceRoot.Name = "edit"; entity.OwnedCollectionRoot[0].OwnedCollectionBranch[1].OwnedCollectionLeaf[0].SomethingSomething = "yet another change"; entity.OwnedCollectionRoot[0].OwnedCollectionBranch[1].OwnedCollectionLeaf[1].SomethingSomething = "and another"; @@ -612,7 +610,7 @@ public virtual Task Edit_element_in_json_multiple_levels_partial_update() async context => { var result = await context.Set().SingleAsync(); - Assert.Equal(new DateTime(2111, 11, 11), result.OwnedReferenceRoot.OwnedReferenceBranch.Date); + Assert.Equal(new DateTime(2111, 11, 11), result.OwnedReferenceRoot.OwnedReferenceBranch!.Date); Assert.Equal("edit", result.OwnedReferenceRoot.Name); Assert.Equal( "yet another change", result.OwnedCollectionRoot[0].OwnedCollectionBranch[1].OwnedCollectionLeaf[0].SomethingSomething); @@ -732,7 +730,7 @@ public virtual Task Edit_single_enum_property() { var query = await context.JsonEntitiesBasic.ToListAsync(); var entity = query.Single(); - entity.OwnedReferenceRoot.OwnedReferenceBranch.Enum = JsonEnum.Two; + entity.OwnedReferenceRoot.OwnedReferenceBranch!.Enum = JsonEnum.Two; entity.OwnedCollectionRoot[1].OwnedCollectionBranch[1].Enum = JsonEnum.Two; ClearLog(); @@ -741,7 +739,7 @@ public virtual Task Edit_single_enum_property() async context => { var result = await context.Set().SingleAsync(); - Assert.Equal(JsonEnum.Two, result.OwnedReferenceRoot.OwnedReferenceBranch.Enum); + Assert.Equal(JsonEnum.Two, result.OwnedReferenceRoot.OwnedReferenceBranch!.Enum); Assert.Equal(JsonEnum.Two, result.OwnedCollectionRoot[1].OwnedCollectionBranch[1].Enum); }); @@ -776,7 +774,7 @@ public virtual Task Edit_single_property_bool() { var query = await context.JsonEntitiesAllTypes.ToListAsync(); var entity = query.Single(x => x.Id == 1); - entity.Reference.TestBoolean = false; + entity.Reference!.TestBoolean = false; entity.Collection[0].TestBoolean = true; ClearLog(); @@ -785,7 +783,7 @@ public virtual Task Edit_single_property_bool() async context => { var result = await context.Set().SingleAsync(x => x.Id == 1); - Assert.False(result.Reference.TestBoolean); + Assert.False(result.Reference!.TestBoolean); Assert.True(result.Collection[0].TestBoolean); }); @@ -798,7 +796,7 @@ public virtual Task Edit_single_property_byte() { var query = await context.JsonEntitiesAllTypes.ToListAsync(); var entity = query.Single(x => x.Id == 1); - entity.Reference.TestByte = 25; + entity.Reference!.TestByte = 25; entity.Collection[0].TestByte = 14; ClearLog(); @@ -807,7 +805,7 @@ public virtual Task Edit_single_property_byte() async context => { var result = await context.Set().SingleAsync(x => x.Id == 1); - Assert.Equal(25, result.Reference.TestByte); + Assert.Equal(25, result.Reference!.TestByte); Assert.Equal(14, result.Collection[0].TestByte); }); @@ -820,7 +818,7 @@ public virtual Task Edit_single_property_char() { var query = await context.JsonEntitiesAllTypes.ToListAsync(); var entity = query.Single(x => x.Id == 1); - entity.Reference.TestCharacter = 't'; + entity.Reference!.TestCharacter = 't'; entity.Collection[0].TestCharacter = 'h'; ClearLog(); @@ -829,7 +827,7 @@ public virtual Task Edit_single_property_char() async context => { var result = await context.Set().SingleAsync(x => x.Id == 1); - Assert.Equal('t', result.Reference.TestCharacter); + Assert.Equal('t', result.Reference!.TestCharacter); Assert.Equal('h', result.Collection[0].TestCharacter); }); @@ -842,7 +840,7 @@ public virtual Task Edit_single_property_datetime() { var query = await context.JsonEntitiesAllTypes.ToListAsync(); var entity = query.Single(x => x.Id == 1); - entity.Reference.TestDateTime = DateTime.Parse("01/01/3000 12:34:56"); + entity.Reference!.TestDateTime = DateTime.Parse("01/01/3000 12:34:56"); entity.Collection[0].TestDateTime = DateTime.Parse("01/01/3000 12:34:56"); ClearLog(); @@ -851,7 +849,7 @@ public virtual Task Edit_single_property_datetime() async context => { var result = await context.Set().SingleAsync(x => x.Id == 1); - Assert.Equal(DateTime.Parse("01/01/3000 12:34:56"), result.Reference.TestDateTime); + Assert.Equal(DateTime.Parse("01/01/3000 12:34:56"), result.Reference!.TestDateTime); Assert.Equal(DateTime.Parse("01/01/3000 12:34:56"), result.Collection[0].TestDateTime); }); @@ -864,7 +862,7 @@ public virtual Task Edit_single_property_datetimeoffset() { var query = await context.JsonEntitiesAllTypes.ToListAsync(); var entity = query.Single(x => x.Id == 1); - entity.Reference.TestDateTimeOffset = new DateTimeOffset(DateTime.Parse("01/01/3000 12:34:56"), TimeSpan.FromHours(-4.0)); + entity.Reference!.TestDateTimeOffset = new DateTimeOffset(DateTime.Parse("01/01/3000 12:34:56"), TimeSpan.FromHours(-4.0)); entity.Collection[0].TestDateTimeOffset = new DateTimeOffset( DateTime.Parse("01/01/3000 12:34:56"), TimeSpan.FromHours(-4.0)); @@ -876,7 +874,7 @@ public virtual Task Edit_single_property_datetimeoffset() var result = await context.Set().SingleAsync(x => x.Id == 1); Assert.Equal( new DateTimeOffset(DateTime.Parse("01/01/3000 12:34:56"), TimeSpan.FromHours(-4.0)), - result.Reference.TestDateTimeOffset); + result.Reference!.TestDateTimeOffset); Assert.Equal( new DateTimeOffset(DateTime.Parse("01/01/3000 12:34:56"), TimeSpan.FromHours(-4.0)), result.Collection[0].TestDateTimeOffset); @@ -891,7 +889,7 @@ public virtual Task Edit_single_property_decimal() { var query = await context.JsonEntitiesAllTypes.ToListAsync(); var entity = query.Single(x => x.Id == 1); - entity.Reference.TestDecimal = -13579.01M; + entity.Reference!.TestDecimal = -13579.01M; entity.Collection[0].TestDecimal = -13579.01M; ClearLog(); @@ -900,7 +898,7 @@ public virtual Task Edit_single_property_decimal() async context => { var result = await context.Set().SingleAsync(x => x.Id == 1); - Assert.Equal(-13579.01M, result.Reference.TestDecimal); + Assert.Equal(-13579.01M, result.Reference!.TestDecimal); Assert.Equal(-13579.01M, result.Collection[0].TestDecimal); }); @@ -913,7 +911,7 @@ public virtual Task Edit_single_property_double() { var query = await context.JsonEntitiesAllTypes.ToListAsync(); var entity = query.Single(x => x.Id == 1); - entity.Reference.TestDouble = -1.23579; + entity.Reference!.TestDouble = -1.23579; entity.Collection[0].TestDouble = -1.23579; ClearLog(); @@ -922,7 +920,7 @@ public virtual Task Edit_single_property_double() async context => { var result = await context.Set().SingleAsync(x => x.Id == 1); - Assert.Equal(-1.23579, result.Reference.TestDouble); + Assert.Equal(-1.23579, result.Reference!.TestDouble); Assert.Equal(-1.23579, result.Collection[0].TestDouble); }); @@ -935,7 +933,7 @@ public virtual Task Edit_single_property_guid() { var query = await context.JsonEntitiesAllTypes.ToListAsync(); var entity = query.Single(x => x.Id == 1); - entity.Reference.TestGuid = new Guid("12345678-1234-4321-5555-987654321000"); + entity.Reference!.TestGuid = new Guid("12345678-1234-4321-5555-987654321000"); entity.Collection[0].TestGuid = new Guid("12345678-1234-4321-5555-987654321000"); ClearLog(); @@ -944,7 +942,7 @@ public virtual Task Edit_single_property_guid() async context => { var result = await context.Set().SingleAsync(x => x.Id == 1); - Assert.Equal(new Guid("12345678-1234-4321-5555-987654321000"), result.Reference.TestGuid); + Assert.Equal(new Guid("12345678-1234-4321-5555-987654321000"), result.Reference!.TestGuid); Assert.Equal(new Guid("12345678-1234-4321-5555-987654321000"), result.Collection[0].TestGuid); }); @@ -957,7 +955,7 @@ public virtual Task Edit_single_property_int16() { var query = await context.JsonEntitiesAllTypes.ToListAsync(); var entity = query.Single(x => x.Id == 1); - entity.Reference.TestInt16 = -3234; + entity.Reference!.TestInt16 = -3234; entity.Collection[0].TestInt16 = -3234; ClearLog(); @@ -966,7 +964,7 @@ public virtual Task Edit_single_property_int16() async context => { var result = await context.Set().SingleAsync(x => x.Id == 1); - Assert.Equal(-3234, result.Reference.TestInt16); + Assert.Equal(-3234, result.Reference!.TestInt16); Assert.Equal(-3234, result.Collection[0].TestInt16); }); @@ -979,7 +977,7 @@ public virtual Task Edit_single_property_int32() { var query = await context.JsonEntitiesAllTypes.ToListAsync(); var entity = query.Single(x => x.Id == 1); - entity.Reference.TestInt32 = -3234; + entity.Reference!.TestInt32 = -3234; entity.Collection[0].TestInt32 = -3234; ClearLog(); @@ -988,7 +986,7 @@ public virtual Task Edit_single_property_int32() async context => { var result = await context.Set().SingleAsync(x => x.Id == 1); - Assert.Equal(-3234, result.Reference.TestInt32); + Assert.Equal(-3234, result.Reference!.TestInt32); Assert.Equal(-3234, result.Collection[0].TestInt32); }); @@ -1001,7 +999,7 @@ public virtual Task Edit_single_property_int64() { var query = await context.JsonEntitiesAllTypes.ToListAsync(); var entity = query.Single(x => x.Id == 1); - entity.Reference.TestInt64 = -3234; + entity.Reference!.TestInt64 = -3234; entity.Collection[0].TestInt64 = -3234; ClearLog(); @@ -1010,7 +1008,7 @@ public virtual Task Edit_single_property_int64() async context => { var result = await context.Set().SingleAsync(x => x.Id == 1); - Assert.Equal(-3234, result.Reference.TestInt64); + Assert.Equal(-3234, result.Reference!.TestInt64); Assert.Equal(-3234, result.Collection[0].TestInt64); }); @@ -1023,7 +1021,7 @@ public virtual Task Edit_single_property_signed_byte() { var query = await context.JsonEntitiesAllTypes.ToListAsync(); var entity = query.Single(x => x.Id == 1); - entity.Reference.TestSignedByte = -108; + entity.Reference!.TestSignedByte = -108; entity.Collection[0].TestSignedByte = -108; ClearLog(); @@ -1032,7 +1030,7 @@ public virtual Task Edit_single_property_signed_byte() async context => { var result = await context.Set().SingleAsync(x => x.Id == 1); - Assert.Equal(-108, result.Reference.TestSignedByte); + Assert.Equal(-108, result.Reference!.TestSignedByte); Assert.Equal(-108, result.Collection[0].TestSignedByte); }); @@ -1045,7 +1043,7 @@ public virtual Task Edit_single_property_single() { var query = await context.JsonEntitiesAllTypes.ToListAsync(); var entity = query.Single(x => x.Id == 1); - entity.Reference.TestSingle = -7.234F; + entity.Reference!.TestSingle = -7.234F; entity.Collection[0].TestSingle = -7.234F; ClearLog(); @@ -1054,7 +1052,7 @@ public virtual Task Edit_single_property_single() async context => { var result = await context.Set().SingleAsync(x => x.Id == 1); - Assert.Equal(-7.234F, result.Reference.TestSingle); + Assert.Equal(-7.234F, result.Reference!.TestSingle); Assert.Equal(-7.234F, result.Collection[0].TestSingle); }); @@ -1067,7 +1065,7 @@ public virtual Task Edit_single_property_timespan() { var query = await context.JsonEntitiesAllTypes.ToListAsync(); var entity = query.Single(x => x.Id == 1); - entity.Reference.TestTimeSpan = new TimeSpan(0, 10, 1, 1, 7); + entity.Reference!.TestTimeSpan = new TimeSpan(0, 10, 1, 1, 7); entity.Collection[0].TestTimeSpan = new TimeSpan(0, 10, 1, 1, 7); ClearLog(); @@ -1076,7 +1074,7 @@ public virtual Task Edit_single_property_timespan() async context => { var result = await context.Set().SingleAsync(x => x.Id == 1); - Assert.Equal(new TimeSpan(0, 10, 1, 1, 7), result.Reference.TestTimeSpan); + Assert.Equal(new TimeSpan(0, 10, 1, 1, 7), result.Reference!.TestTimeSpan); Assert.Equal(new TimeSpan(0, 10, 1, 1, 7), result.Collection[0].TestTimeSpan); }); @@ -1089,7 +1087,7 @@ public virtual Task Edit_single_property_dateonly() { var query = await context.JsonEntitiesAllTypes.ToListAsync(); var entity = query.Single(x => x.Id == 1); - entity.Reference.TestDateOnly = new DateOnly(1023, 1, 1); + entity.Reference!.TestDateOnly = new DateOnly(1023, 1, 1); entity.Collection[0].TestDateOnly = new DateOnly(2000, 2, 4); ClearLog(); @@ -1098,7 +1096,7 @@ public virtual Task Edit_single_property_dateonly() async context => { var result = await context.Set().SingleAsync(x => x.Id == 1); - Assert.Equal(new DateOnly(1023, 1, 1), result.Reference.TestDateOnly); + Assert.Equal(new DateOnly(1023, 1, 1), result.Reference!.TestDateOnly); Assert.Equal(new DateOnly(2000, 2, 4), result.Collection[0].TestDateOnly); }); @@ -1111,7 +1109,7 @@ public virtual Task Edit_single_property_timeonly() { var query = await context.JsonEntitiesAllTypes.ToListAsync(); var entity = query.Single(x => x.Id == 1); - entity.Reference.TestTimeOnly = new TimeOnly(1, 1, 7); + entity.Reference!.TestTimeOnly = new TimeOnly(1, 1, 7); entity.Collection[0].TestTimeOnly = new TimeOnly(1, 1, 7); ClearLog(); @@ -1120,7 +1118,7 @@ public virtual Task Edit_single_property_timeonly() async context => { var result = await context.Set().SingleAsync(x => x.Id == 1); - Assert.Equal(new TimeOnly(1, 1, 7), result.Reference.TestTimeOnly); + Assert.Equal(new TimeOnly(1, 1, 7), result.Reference!.TestTimeOnly); Assert.Equal(new TimeOnly(1, 1, 7), result.Collection[0].TestTimeOnly); }); @@ -1133,7 +1131,7 @@ public virtual Task Edit_single_property_uint16() { var query = await context.JsonEntitiesAllTypes.ToListAsync(); var entity = query.Single(x => x.Id == 1); - entity.Reference.TestUnsignedInt16 = 1534; + entity.Reference!.TestUnsignedInt16 = 1534; entity.Collection[0].TestUnsignedInt16 = 1534; ClearLog(); @@ -1142,7 +1140,7 @@ public virtual Task Edit_single_property_uint16() async context => { var result = await context.Set().SingleAsync(x => x.Id == 1); - Assert.Equal(1534, result.Reference.TestUnsignedInt16); + Assert.Equal(1534, result.Reference!.TestUnsignedInt16); Assert.Equal(1534, result.Collection[0].TestUnsignedInt16); }); @@ -1155,7 +1153,7 @@ public virtual Task Edit_single_property_uint32() { var query = await context.JsonEntitiesAllTypes.ToListAsync(); var entity = query.Single(x => x.Id == 1); - entity.Reference.TestUnsignedInt32 = 1237775789U; + entity.Reference!.TestUnsignedInt32 = 1237775789U; entity.Collection[0].TestUnsignedInt32 = 1237775789U; ClearLog(); @@ -1164,7 +1162,7 @@ public virtual Task Edit_single_property_uint32() async context => { var result = await context.Set().SingleAsync(x => x.Id == 1); - Assert.Equal(1237775789U, result.Reference.TestUnsignedInt32); + Assert.Equal(1237775789U, result.Reference!.TestUnsignedInt32); Assert.Equal(1237775789U, result.Collection[0].TestUnsignedInt32); }); @@ -1177,7 +1175,7 @@ public virtual Task Edit_single_property_uint64() { var query = await context.JsonEntitiesAllTypes.ToListAsync(); var entity = query.Single(x => x.Id == 1); - entity.Reference.TestUnsignedInt64 = 1234555555123456789UL; + entity.Reference!.TestUnsignedInt64 = 1234555555123456789UL; entity.Collection[0].TestUnsignedInt64 = 1234555555123456789UL; ClearLog(); @@ -1186,7 +1184,7 @@ public virtual Task Edit_single_property_uint64() async context => { var result = await context.Set().SingleAsync(x => x.Id == 1); - Assert.Equal(1234555555123456789UL, result.Reference.TestUnsignedInt64); + Assert.Equal(1234555555123456789UL, result.Reference!.TestUnsignedInt64); Assert.Equal(1234555555123456789UL, result.Collection[0].TestUnsignedInt64); }); @@ -1199,7 +1197,7 @@ public virtual Task Edit_single_property_nullable_int32() { var query = await context.JsonEntitiesAllTypes.ToListAsync(); var entity = query.Single(x => x.Id == 1); - entity.Reference.TestNullableInt32 = 64528; + entity.Reference!.TestNullableInt32 = 64528; entity.Collection[0].TestNullableInt32 = 122354; ClearLog(); @@ -1208,7 +1206,7 @@ public virtual Task Edit_single_property_nullable_int32() async context => { var result = await context.Set().SingleAsync(x => x.Id == 1); - Assert.Equal(64528, result.Reference.TestNullableInt32); + Assert.Equal(64528, result.Reference!.TestNullableInt32); Assert.Equal(122354, result.Collection[0].TestNullableInt32); }); @@ -1221,7 +1219,7 @@ public virtual Task Edit_single_property_nullable_int32_set_to_null() { var query = await context.JsonEntitiesAllTypes.ToListAsync(); var entity = query.Single(x => x.Id == 1); - entity.Reference.TestNullableInt32 = null; + entity.Reference!.TestNullableInt32 = null; entity.Collection[0].TestNullableInt32 = null; ClearLog(); @@ -1230,7 +1228,7 @@ public virtual Task Edit_single_property_nullable_int32_set_to_null() async context => { var result = await context.Set().SingleAsync(x => x.Id == 1); - Assert.Null(result.Reference.TestNullableInt32); + Assert.Null(result.Reference!.TestNullableInt32); Assert.Null(result.Collection[0].TestNullableInt32); }); @@ -1243,7 +1241,7 @@ public virtual Task Edit_single_property_nullable_datetime_set_to_null() { var query = await context.JsonEntitiesAllTypes.ToListAsync(); var entity = query.Single(x => x.Id == 1); - entity.Reference.TestNullableDateTime = null; + entity.Reference!.TestNullableDateTime = null; entity.Collection[0].TestNullableDateTime = null; ClearLog(); @@ -1252,7 +1250,7 @@ public virtual Task Edit_single_property_nullable_datetime_set_to_null() async context => { var result = await context.Set().SingleAsync(x => x.Id == 1); - Assert.Null(result.Reference.TestNullableDateTime); + Assert.Null(result.Reference!.TestNullableDateTime); Assert.Null(result.Collection[0].TestNullableDateTime); }); @@ -1265,7 +1263,7 @@ public virtual Task Edit_single_property_nullable_dateonly_set_to_null() { var query = await context.JsonEntitiesAllTypes.ToListAsync(); var entity = query.Single(x => x.Id == 1); - entity.Reference.TestNullableDateOnly = null; + entity.Reference!.TestNullableDateOnly = null; entity.Collection[0].TestNullableDateOnly = null; ClearLog(); @@ -1274,7 +1272,7 @@ public virtual Task Edit_single_property_nullable_dateonly_set_to_null() async context => { var result = await context.Set().SingleAsync(x => x.Id == 1); - Assert.Null(result.Reference.TestNullableDateOnly); + Assert.Null(result.Reference!.TestNullableDateOnly); Assert.Null(result.Collection[0].TestNullableDateOnly); }); @@ -1287,7 +1285,7 @@ public virtual Task Edit_single_property_enum() { var query = await context.JsonEntitiesAllTypes.ToListAsync(); var entity = query.Single(x => x.Id == 1); - entity.Reference.TestEnum = JsonEnum.Three; + entity.Reference!.TestEnum = JsonEnum.Three; entity.Collection[0].TestEnum = JsonEnum.Three; ClearLog(); @@ -1296,7 +1294,7 @@ public virtual Task Edit_single_property_enum() async context => { var result = await context.Set().SingleAsync(x => x.Id == 1); - Assert.Equal(JsonEnum.Three, result.Reference.TestEnum); + Assert.Equal(JsonEnum.Three, result.Reference!.TestEnum); Assert.Equal(JsonEnum.Three, result.Collection[0].TestEnum); }); @@ -1309,7 +1307,7 @@ public virtual Task Edit_single_property_enum_with_int_converter() { var query = await context.JsonEntitiesAllTypes.ToListAsync(); var entity = query.Single(x => x.Id == 1); - entity.Reference.TestEnumWithIntConverter = JsonEnum.Three; + entity.Reference!.TestEnumWithIntConverter = JsonEnum.Three; entity.Collection[0].TestEnumWithIntConverter = JsonEnum.Three; ClearLog(); @@ -1318,7 +1316,7 @@ public virtual Task Edit_single_property_enum_with_int_converter() async context => { var result = await context.Set().SingleAsync(x => x.Id == 1); - Assert.Equal(JsonEnum.Three, result.Reference.TestEnumWithIntConverter); + Assert.Equal(JsonEnum.Three, result.Reference!.TestEnumWithIntConverter); Assert.Equal(JsonEnum.Three, result.Collection[0].TestEnumWithIntConverter); }); @@ -1331,7 +1329,7 @@ public virtual Task Edit_single_property_nullable_enum() { var query = await context.JsonEntitiesAllTypes.ToListAsync(); var entity = query.Single(x => x.Id == 1); - entity.Reference.TestEnum = JsonEnum.Three; + entity.Reference!.TestEnum = JsonEnum.Three; entity.Collection[0].TestEnum = JsonEnum.Three; ClearLog(); @@ -1340,7 +1338,7 @@ public virtual Task Edit_single_property_nullable_enum() async context => { var result = await context.Set().SingleAsync(x => x.Id == 1); - Assert.Equal(JsonEnum.Three, result.Reference.TestEnum); + Assert.Equal(JsonEnum.Three, result.Reference!.TestEnum); Assert.Equal(JsonEnum.Three, result.Collection[0].TestEnum); }); @@ -1353,7 +1351,7 @@ public virtual Task Edit_single_property_nullable_enum_set_to_null() { var query = await context.JsonEntitiesAllTypes.ToListAsync(); var entity = query.Single(x => x.Id == 1); - entity.Reference.TestNullableEnum = null; + entity.Reference!.TestNullableEnum = null; entity.Collection[0].TestNullableEnum = null; ClearLog(); @@ -1362,7 +1360,7 @@ public virtual Task Edit_single_property_nullable_enum_set_to_null() async context => { var result = await context.Set().SingleAsync(x => x.Id == 1); - Assert.Null(result.Reference.TestNullableEnum); + Assert.Null(result.Reference!.TestNullableEnum); Assert.Null(result.Collection[0].TestNullableEnum); }); @@ -1375,7 +1373,7 @@ public virtual Task Edit_single_property_nullable_enum_with_int_converter() { var query = await context.JsonEntitiesAllTypes.ToListAsync(); var entity = query.Single(x => x.Id == 1); - entity.Reference.TestNullableEnumWithIntConverter = JsonEnum.Three; + entity.Reference!.TestNullableEnumWithIntConverter = JsonEnum.Three; entity.Collection[0].TestNullableEnumWithIntConverter = JsonEnum.One; ClearLog(); @@ -1384,7 +1382,7 @@ public virtual Task Edit_single_property_nullable_enum_with_int_converter() async context => { var result = await context.Set().SingleAsync(x => x.Id == 1); - Assert.Equal(JsonEnum.Three, result.Reference.TestNullableEnumWithIntConverter); + Assert.Equal(JsonEnum.Three, result.Reference!.TestNullableEnumWithIntConverter); Assert.Equal(JsonEnum.One, result.Collection[0].TestNullableEnumWithIntConverter); }); @@ -1397,7 +1395,7 @@ public virtual Task Edit_single_property_nullable_enum_with_int_converter_set_to { var query = await context.JsonEntitiesAllTypes.ToListAsync(); var entity = query.Single(x => x.Id == 1); - entity.Reference.TestNullableEnumWithIntConverter = null; + entity.Reference!.TestNullableEnumWithIntConverter = null; entity.Collection[0].TestNullableEnumWithIntConverter = null; ClearLog(); @@ -1406,7 +1404,7 @@ public virtual Task Edit_single_property_nullable_enum_with_int_converter_set_to async context => { var result = await context.Set().SingleAsync(x => x.Id == 1); - Assert.Null(result.Reference.TestNullableEnumWithIntConverter); + Assert.Null(result.Reference!.TestNullableEnumWithIntConverter); Assert.Null(result.Collection[0].TestNullableEnumWithIntConverter); }); @@ -1419,7 +1417,7 @@ public virtual Task Edit_single_property_nullable_enum_with_converter_that_handl { var query = await context.JsonEntitiesAllTypes.ToListAsync(); var entity = query.Single(x => x.Id == 1); - entity.Reference.TestNullableEnumWithConverterThatHandlesNulls = JsonEnum.One; + entity.Reference!.TestNullableEnumWithConverterThatHandlesNulls = JsonEnum.One; entity.Collection[0].TestNullableEnumWithConverterThatHandlesNulls = JsonEnum.Three; ClearLog(); @@ -1428,7 +1426,7 @@ public virtual Task Edit_single_property_nullable_enum_with_converter_that_handl async context => { var result = await context.Set().SingleAsync(x => x.Id == 1); - Assert.Equal(JsonEnum.One, result.Reference.TestNullableEnumWithConverterThatHandlesNulls); + Assert.Equal(JsonEnum.One, result.Reference!.TestNullableEnumWithConverterThatHandlesNulls); Assert.Equal(JsonEnum.Three, result.Collection[0].TestNullableEnumWithConverterThatHandlesNulls); }); @@ -1441,7 +1439,7 @@ public virtual Task Edit_single_property_nullable_enum_with_converter_that_handl { var query = await context.JsonEntitiesAllTypes.ToListAsync(); var entity = query.Single(x => x.Id == 1); - entity.Reference.TestNullableEnumWithConverterThatHandlesNulls = null; + entity.Reference!.TestNullableEnumWithConverterThatHandlesNulls = null; entity.Collection[0].TestNullableEnumWithConverterThatHandlesNulls = null; ClearLog(); @@ -1450,7 +1448,7 @@ public virtual Task Edit_single_property_nullable_enum_with_converter_that_handl async context => { var result = await context.Set().SingleAsync(x => x.Id == 1); - Assert.Null(result.Reference.TestNullableEnumWithConverterThatHandlesNulls); + Assert.Null(result.Reference!.TestNullableEnumWithConverterThatHandlesNulls); Assert.Null(result.Collection[0].TestNullableEnumWithConverterThatHandlesNulls); }); @@ -1463,7 +1461,7 @@ public virtual Task Edit_two_properties_on_same_entity_updates_the_entire_entity { var query = await context.JsonEntitiesAllTypes.ToListAsync(); var entity = query.Single(x => x.Id == 1); - entity.Reference.TestInt32 = 32; + entity.Reference!.TestInt32 = 32; entity.Reference.TestInt64 = 64; entity.Collection[0].TestInt32 = 32; entity.Collection[0].TestInt64 = 64; @@ -1474,7 +1472,7 @@ public virtual Task Edit_two_properties_on_same_entity_updates_the_entire_entity async context => { var result = await context.Set().SingleAsync(x => x.Id == 1); - Assert.Equal(32, result.Reference.TestInt32); + Assert.Equal(32, result.Reference!.TestInt32); Assert.Equal(64, result.Reference.TestInt64); Assert.Equal(32, result.Collection[0].TestInt32); Assert.Equal(64, result.Collection[0].TestInt64); @@ -1489,15 +1487,15 @@ public virtual Task Edit_a_scalar_property_and_reference_navigation_on_the_same_ { var query = await context.JsonEntitiesBasic.ToListAsync(); var entity = query.Single(); - entity.OwnedReferenceRoot.OwnedReferenceBranch.Fraction = 123.532M; - entity.OwnedReferenceRoot.OwnedReferenceBranch.OwnedReferenceLeaf = null; + entity.OwnedReferenceRoot.OwnedReferenceBranch!.Fraction = 123.532M; + entity.OwnedReferenceRoot.OwnedReferenceBranch.OwnedReferenceLeaf = null!; await context.SaveChangesAsync(); }, async context => { var query = await context.JsonEntitiesBasic.ToListAsync(); var entity = query.Single(); - entity.OwnedReferenceRoot.OwnedReferenceBranch.Fraction = 523.532M; + entity.OwnedReferenceRoot.OwnedReferenceBranch!.Fraction = 523.532M; entity.OwnedReferenceRoot.OwnedReferenceBranch.OwnedReferenceLeaf = new JsonOwnedLeaf { SomethingSomething = "edit" }; ClearLog(); @@ -1506,7 +1504,7 @@ public virtual Task Edit_a_scalar_property_and_reference_navigation_on_the_same_ async context => { var result = await context.Set().SingleAsync(); - Assert.Equal(523.532M, result.OwnedReferenceRoot.OwnedReferenceBranch.Fraction); + Assert.Equal(523.532M, result.OwnedReferenceRoot.OwnedReferenceBranch!.Fraction); Assert.Equal("edit", result.OwnedReferenceRoot.OwnedReferenceBranch.OwnedReferenceLeaf.SomethingSomething); }); @@ -1519,15 +1517,15 @@ public virtual Task Edit_a_scalar_property_and_collection_navigation_on_the_same { var query = await context.JsonEntitiesBasic.ToListAsync(); var entity = query.Single(); - entity.OwnedReferenceRoot.OwnedReferenceBranch.Fraction = 123.532M; - entity.OwnedReferenceRoot.OwnedReferenceBranch.OwnedCollectionLeaf = null; + entity.OwnedReferenceRoot.OwnedReferenceBranch!.Fraction = 123.532M; + entity.OwnedReferenceRoot.OwnedReferenceBranch.OwnedCollectionLeaf = null!; await context.SaveChangesAsync(); }, async context => { var query = await context.JsonEntitiesBasic.ToListAsync(); var entity = query.Single(); - entity.OwnedReferenceRoot.OwnedReferenceBranch.Fraction = 523.532M; + entity.OwnedReferenceRoot.OwnedReferenceBranch!.Fraction = 523.532M; entity.OwnedReferenceRoot.OwnedReferenceBranch.OwnedCollectionLeaf = [new JsonOwnedLeaf { SomethingSomething = "edit" }]; ClearLog(); @@ -1536,7 +1534,7 @@ public virtual Task Edit_a_scalar_property_and_collection_navigation_on_the_same async context => { var result = await context.Set().SingleAsync(); - Assert.Equal(523.532M, result.OwnedReferenceRoot.OwnedReferenceBranch.Fraction); + Assert.Equal(523.532M, result.OwnedReferenceRoot.OwnedReferenceBranch!.Fraction); Assert.Equal("edit", result.OwnedReferenceRoot.OwnedReferenceBranch.OwnedCollectionLeaf[0].SomethingSomething); }); @@ -1549,7 +1547,7 @@ public virtual Task Edit_a_scalar_property_and_another_property_behind_reference { var query = await context.JsonEntitiesBasic.ToListAsync(); var entity = query.Single(); - entity.OwnedReferenceRoot.OwnedReferenceBranch.Fraction = 523.532M; + entity.OwnedReferenceRoot.OwnedReferenceBranch!.Fraction = 523.532M; entity.OwnedReferenceRoot.OwnedReferenceBranch.OwnedReferenceLeaf.SomethingSomething = "edit"; ClearLog(); @@ -1558,7 +1556,7 @@ public virtual Task Edit_a_scalar_property_and_another_property_behind_reference async context => { var result = await context.Set().SingleAsync(); - Assert.Equal(523.532M, result.OwnedReferenceRoot.OwnedReferenceBranch.Fraction); + Assert.Equal(523.532M, result.OwnedReferenceRoot.OwnedReferenceBranch!.Fraction); Assert.Equal("edit", result.OwnedReferenceRoot.OwnedReferenceBranch.OwnedReferenceLeaf.SomethingSomething); }); @@ -1735,7 +1733,7 @@ public virtual Task Edit_single_property_collection_of_bool() { var query = await context.JsonEntitiesAllTypes.ToListAsync(); var entity = query.Single(x => x.Id == 1); - entity.Reference.TestBooleanCollection = [true, true, false]; + entity.Reference!.TestBooleanCollection = [true, true, false]; entity.Collection[0].TestBooleanCollection = [true, true, true, false]; ClearLog(); @@ -1744,7 +1742,7 @@ public virtual Task Edit_single_property_collection_of_bool() async context => { var result = await context.Set().SingleAsync(x => x.Id == 1); - Assert.Equal([true, true, false], result.Reference.TestBooleanCollection); + Assert.Equal([true, true, false], result.Reference!.TestBooleanCollection); Assert.Equal([true, true, true, false], result.Collection[0].TestBooleanCollection); Assert.False(result.Reference.NewCollectionSet); @@ -1760,7 +1758,7 @@ public virtual Task Edit_single_property_collection_of_byte() { var query = await context.JsonEntitiesAllTypes.ToListAsync(); var entity = query.Single(x => x.Id == 1); - entity.Reference.TestByteCollection = [25, 26]; + entity.Reference!.TestByteCollection = [25, 26]; entity.Collection[0].TestByteCollection = [14]; ClearLog(); @@ -1769,7 +1767,7 @@ public virtual Task Edit_single_property_collection_of_byte() async context => { var result = await context.Set().SingleAsync(x => x.Id == 1); - Assert.Equal(new byte[] { 25, 26 }, result.Reference.TestByteCollection); + Assert.Equal(new byte[] { 25, 26 }, result.Reference!.TestByteCollection); Assert.Equal(new byte[] { 14 }, result.Collection[0].TestByteCollection); Assert.False(result.Reference.NewCollectionSet); @@ -1785,7 +1783,7 @@ public virtual Task Edit_single_property_collection_of_char() { var query = await context.JsonEntitiesAllTypes.ToListAsync(); var entity = query.Single(x => x.Id == 1); - entity.Reference.TestCharacterCollection = + entity.Reference!.TestCharacterCollection = [ 'E', 'F', @@ -1796,7 +1794,7 @@ public virtual Task Edit_single_property_collection_of_char() '\"', '\\' ]; - entity.Collection[0].TestCharacterCollection.Add((char)0); + entity.Collection[0].TestCharacterCollection!.Add((char)0); ClearLog(); await context.SaveChangesAsync(); @@ -1804,7 +1802,7 @@ public virtual Task Edit_single_property_collection_of_char() async context => { var result = await context.Set().SingleAsync(x => x.Id == 1); - Assert.Equal(new[] { 'E', 'F', 'C', 'ö', 'r', 'E', '\"', '\\' }, result.Reference.TestCharacterCollection); + Assert.Equal(new[] { 'E', 'F', 'C', 'ö', 'r', 'E', '\"', '\\' }, result.Reference!.TestCharacterCollection); Assert.Equal(new[] { 'A', 'B', '\"', (char)0 }, result.Collection[0].TestCharacterCollection); Assert.False(result.Reference.NewCollectionSet); @@ -1820,7 +1818,7 @@ public virtual Task Edit_single_property_collection_of_datetime() { var query = await context.JsonEntitiesAllTypes.ToListAsync(); var entity = query.Single(x => x.Id == 1); - entity.Reference.TestDateTimeCollection.Add(DateTime.Parse("01/01/3000 12:34:56")); + entity.Reference!.TestDateTimeCollection.Add(DateTime.Parse("01/01/3000 12:34:56")); entity.Collection[0].TestDateTimeCollection.Add(DateTime.Parse("01/01/3000 12:34:56")); ClearLog(); @@ -1835,7 +1833,7 @@ public virtual Task Edit_single_property_collection_of_datetime() DateTime.Parse("01/01/2000 12:34:56"), DateTime.Parse("01/01/3000 12:34:56"), DateTime.Parse("01/01/3000 12:34:56") - }, result.Reference.TestDateTimeCollection); + }, result.Reference!.TestDateTimeCollection); Assert.Equal( new[] { @@ -1857,7 +1855,7 @@ public virtual Task Edit_single_property_collection_of_datetimeoffset() { var query = await context.JsonEntitiesAllTypes.ToListAsync(); var entity = query.Single(x => x.Id == 1); - entity.Reference.TestDateTimeOffsetCollection = + entity.Reference!.TestDateTimeOffsetCollection = [ new(DateTime.Parse("01/01/3000 12:34:56"), TimeSpan.FromHours(-4.0)) ]; @@ -1874,7 +1872,7 @@ public virtual Task Edit_single_property_collection_of_datetimeoffset() var result = await context.Set().SingleAsync(x => x.Id == 1); Assert.Equal( [new(DateTime.Parse("01/01/3000 12:34:56"), TimeSpan.FromHours(-4.0))], - result.Reference.TestDateTimeOffsetCollection); + result.Reference!.TestDateTimeOffsetCollection); Assert.Equal( [new(DateTime.Parse("01/01/3000 12:34:56"), TimeSpan.FromHours(-4.0))], result.Collection[0].TestDateTimeOffsetCollection); @@ -1892,7 +1890,7 @@ public virtual Task Edit_single_property_collection_of_decimal() { var query = await context.JsonEntitiesAllTypes.ToListAsync(); var entity = query.Single(x => x.Id == 1); - entity.Reference.TestDecimalCollection = [-13579.01M]; + entity.Reference!.TestDecimalCollection = [-13579.01M]; entity.Collection[0].TestDecimalCollection = [-13579.01M]; ClearLog(); @@ -1901,7 +1899,7 @@ public virtual Task Edit_single_property_collection_of_decimal() async context => { var result = await context.Set().SingleAsync(x => x.Id == 1); - Assert.Equal(new[] { -13579.01M }, result.Reference.TestDecimalCollection); + Assert.Equal(new[] { -13579.01M }, result.Reference!.TestDecimalCollection); Assert.Equal(new[] { -13579.01M }, result.Collection[0].TestDecimalCollection); Assert.False(result.Reference.NewCollectionSet); @@ -1917,7 +1915,7 @@ public virtual Task Edit_single_property_collection_of_double() { var query = await context.JsonEntitiesAllTypes.ToListAsync(); var entity = query.Single(x => x.Id == 1); - entity.Reference.TestDoubleCollection.Add(-1.23579); + entity.Reference!.TestDoubleCollection.Add(-1.23579); entity.Collection[0].TestDoubleCollection.Add(-1.23579); ClearLog(); @@ -1926,7 +1924,7 @@ public virtual Task Edit_single_property_collection_of_double() async context => { var result = await context.Set().SingleAsync(x => x.Id == 1); - Assert.Equal([-1.23456789, 1.23456789, 0.0, -1.23579], result.Reference.TestDoubleCollection); + Assert.Equal([-1.23456789, 1.23456789, 0.0, -1.23579], result.Reference!.TestDoubleCollection); Assert.Equal([-1.23456789, 1.23456789, 0.0, -1.23579], result.Collection[0].TestDoubleCollection); Assert.False(result.Reference.NewCollectionSet); @@ -1942,7 +1940,7 @@ public virtual Task Edit_single_property_collection_of_guid() { var query = await context.JsonEntitiesAllTypes.ToListAsync(); var entity = query.Single(x => x.Id == 1); - entity.Reference.TestGuidCollection = [new Guid("12345678-1234-4321-5555-987654321000")]; + entity.Reference!.TestGuidCollection = [new Guid("12345678-1234-4321-5555-987654321000")]; entity.Collection[0].TestGuidCollection = [new Guid("12345678-1234-4321-5555-987654321000")]; ClearLog(); @@ -1951,7 +1949,7 @@ public virtual Task Edit_single_property_collection_of_guid() async context => { var result = await context.Set().SingleAsync(x => x.Id == 1); - Assert.Equal([new Guid("12345678-1234-4321-5555-987654321000")], result.Reference.TestGuidCollection); + Assert.Equal([new Guid("12345678-1234-4321-5555-987654321000")], result.Reference!.TestGuidCollection); Assert.Equal([new Guid("12345678-1234-4321-5555-987654321000")], result.Collection[0].TestGuidCollection); Assert.False(result.Reference.NewCollectionSet); @@ -1967,7 +1965,7 @@ public virtual Task Edit_single_property_collection_of_int16() { var query = await context.JsonEntitiesAllTypes.ToListAsync(); var entity = query.Single(x => x.Id == 1); - entity.Reference.TestInt16Collection = [-3234]; + entity.Reference!.TestInt16Collection = [-3234]; entity.Collection[0].TestInt16Collection = [-3234]; ClearLog(); @@ -1976,7 +1974,7 @@ public virtual Task Edit_single_property_collection_of_int16() async context => { var result = await context.Set().SingleAsync(x => x.Id == 1); - Assert.Equal([-3234], result.Reference.TestInt16Collection); + Assert.Equal([-3234], result.Reference!.TestInt16Collection); Assert.Equal([-3234], result.Collection[0].TestInt16Collection); Assert.False(result.Reference.NewCollectionSet); @@ -1992,7 +1990,7 @@ public virtual Task Edit_single_property_collection_of_int32() { var query = await context.JsonEntitiesAllTypes.ToListAsync(); var entity = query.Single(x => x.Id == 1); - entity.Reference.TestInt32Collection = [-3234]; + entity.Reference!.TestInt32Collection = [-3234]; entity.Collection[0].TestInt32Collection = [-3234]; ClearLog(); @@ -2001,7 +1999,7 @@ public virtual Task Edit_single_property_collection_of_int32() async context => { var result = await context.Set().SingleAsync(x => x.Id == 1); - Assert.Equal(new[] { -3234 }, result.Reference.TestInt32Collection); + Assert.Equal(new[] { -3234 }, result.Reference!.TestInt32Collection); Assert.Equal(new[] { -3234 }, result.Collection[0].TestInt32Collection); Assert.False(result.Reference.NewCollectionSet); @@ -2017,7 +2015,7 @@ public virtual Task Edit_single_property_collection_of_int64() { var query = await context.JsonEntitiesAllTypes.ToListAsync(); var entity = query.Single(x => x.Id == 1); - entity.Reference.TestInt64Collection.Clear(); + entity.Reference!.TestInt64Collection.Clear(); entity.Collection[0].TestInt64Collection.Clear(); ClearLog(); @@ -2026,7 +2024,7 @@ public virtual Task Edit_single_property_collection_of_int64() async context => { var result = await context.Set().SingleAsync(x => x.Id == 1); - Assert.Empty(result.Reference.TestInt64Collection); + Assert.Empty(result.Reference!.TestInt64Collection); Assert.Empty(result.Collection[0].TestInt64Collection); Assert.False(result.Reference.NewCollectionSet); @@ -2042,7 +2040,7 @@ public virtual Task Edit_single_property_collection_of_signed_byte() { var query = await context.JsonEntitiesAllTypes.ToListAsync(); var entity = query.Single(x => x.Id == 1); - entity.Reference.TestSignedByteCollection = [-108]; + entity.Reference!.TestSignedByteCollection = [-108]; entity.Collection[0].TestSignedByteCollection = [-108]; ClearLog(); @@ -2051,7 +2049,7 @@ public virtual Task Edit_single_property_collection_of_signed_byte() async context => { var result = await context.Set().SingleAsync(x => x.Id == 1); - Assert.Equal(new sbyte[] { -108 }, result.Reference.TestSignedByteCollection); + Assert.Equal(new sbyte[] { -108 }, result.Reference!.TestSignedByteCollection); Assert.Equal(new sbyte[] { -108 }, result.Collection[0].TestSignedByteCollection); Assert.False(result.Reference.NewCollectionSet); @@ -2067,7 +2065,7 @@ public virtual Task Edit_single_property_collection_of_single() { var query = await context.JsonEntitiesAllTypes.ToListAsync(); var entity = query.Single(x => x.Id == 1); - entity.Reference.TestSingleCollection.RemoveAt(0); + entity.Reference!.TestSingleCollection.RemoveAt(0); entity.Collection[0].TestSingleCollection.RemoveAt(1); ClearLog(); @@ -2076,7 +2074,7 @@ public virtual Task Edit_single_property_collection_of_single() async context => { var result = await context.Set().SingleAsync(x => x.Id == 1); - Assert.Equal(new[] { 0.0F, -1.234F }, result.Reference.TestSingleCollection); + Assert.Equal(new[] { 0.0F, -1.234F }, result.Reference!.TestSingleCollection); Assert.Equal(new[] { -1.234F, -1.234F }, result.Collection[0].TestSingleCollection); Assert.False(result.Reference.NewCollectionSet); @@ -2092,7 +2090,7 @@ public virtual Task Edit_single_property_collection_of_timespan() { var query = await context.JsonEntitiesAllTypes.ToListAsync(); var entity = query.Single(x => x.Id == 1); - entity.Reference.TestTimeSpanCollection[0] = new TimeSpan(0, 10, 1, 1, 7); + entity.Reference!.TestTimeSpanCollection[0] = new TimeSpan(0, 10, 1, 1, 7); entity.Collection[0].TestTimeSpanCollection[1] = new TimeSpan(0, 10, 1, 1, 7); ClearLog(); @@ -2102,7 +2100,7 @@ public virtual Task Edit_single_property_collection_of_timespan() { var result = await context.Set().SingleAsync(x => x.Id == 1); Assert.Equal( - new[] { new TimeSpan(0, 10, 1, 1, 7), new TimeSpan(0, -10, 9, 8, 7) }, result.Reference.TestTimeSpanCollection); + new[] { new TimeSpan(0, 10, 1, 1, 7), new TimeSpan(0, -10, 9, 8, 7) }, result.Reference!.TestTimeSpanCollection); Assert.Equal( new[] { new TimeSpan(0, 10, 9, 8, 7), new TimeSpan(0, 10, 1, 1, 7) }, result.Collection[0].TestTimeSpanCollection); @@ -2119,7 +2117,7 @@ public virtual Task Edit_single_property_collection_of_dateonly() { var query = await context.JsonEntitiesAllTypes.ToListAsync(); var entity = query.Single(x => x.Id == 1); - entity.Reference.TestDateOnlyCollection[0] = new DateOnly(1, 1, 7); + entity.Reference!.TestDateOnlyCollection[0] = new DateOnly(1, 1, 7); entity.Collection[0].TestDateOnlyCollection[1] = new DateOnly(1, 1, 7); ClearLog(); @@ -2129,7 +2127,7 @@ public virtual Task Edit_single_property_collection_of_dateonly() { var result = await context.Set().SingleAsync(x => x.Id == 1); Assert.Equal( - new[] { new DateOnly(1, 1, 7), new DateOnly(4321, 1, 21) }, result.Reference.TestDateOnlyCollection); + new[] { new DateOnly(1, 1, 7), new DateOnly(4321, 1, 21) }, result.Reference!.TestDateOnlyCollection); Assert.Equal( new[] { new DateOnly(3234, 1, 23), new DateOnly(1, 1, 7) }, result.Collection[0].TestDateOnlyCollection); @@ -2146,7 +2144,7 @@ public virtual Task Edit_single_property_collection_of_timeonly() { var query = await context.JsonEntitiesAllTypes.ToListAsync(); var entity = query.Single(x => x.Id == 1); - entity.Reference.TestTimeOnlyCollection[0] = new TimeOnly(1, 1, 7); + entity.Reference!.TestTimeOnlyCollection[0] = new TimeOnly(1, 1, 7); entity.Collection[0].TestTimeOnlyCollection[1] = new TimeOnly(1, 1, 7); ClearLog(); @@ -2156,7 +2154,7 @@ public virtual Task Edit_single_property_collection_of_timeonly() { var result = await context.Set().SingleAsync(x => x.Id == 1); Assert.Equal( - new[] { new TimeOnly(1, 1, 7), new TimeOnly(7, 17, 27) }, result.Reference.TestTimeOnlyCollection); + new[] { new TimeOnly(1, 1, 7), new TimeOnly(7, 17, 27) }, result.Reference!.TestTimeOnlyCollection); Assert.Equal( new[] { new TimeOnly(13, 42, 23), new TimeOnly(1, 1, 7) }, result.Collection[0].TestTimeOnlyCollection); @@ -2173,7 +2171,7 @@ public virtual Task Edit_single_property_collection_of_uint16() { var query = await context.JsonEntitiesAllTypes.ToListAsync(); var entity = query.Single(x => x.Id == 1); - entity.Reference.TestUnsignedInt16Collection = [1534]; + entity.Reference!.TestUnsignedInt16Collection = [1534]; entity.Collection[0].TestUnsignedInt16Collection = [1534]; ClearLog(); @@ -2182,7 +2180,7 @@ public virtual Task Edit_single_property_collection_of_uint16() async context => { var result = await context.Set().SingleAsync(x => x.Id == 1); - Assert.Equal([1534], result.Reference.TestUnsignedInt16Collection); + Assert.Equal([1534], result.Reference!.TestUnsignedInt16Collection); Assert.Equal([1534], result.Collection[0].TestUnsignedInt16Collection); Assert.False(result.Reference.NewCollectionSet); @@ -2198,7 +2196,7 @@ public virtual Task Edit_single_property_collection_of_uint32() { var query = await context.JsonEntitiesAllTypes.ToListAsync(); var entity = query.Single(x => x.Id == 1); - entity.Reference.TestUnsignedInt32Collection = [1237775789U]; + entity.Reference!.TestUnsignedInt32Collection = [1237775789U]; entity.Collection[0].TestUnsignedInt32Collection = [1237775789U]; ClearLog(); @@ -2207,7 +2205,7 @@ public virtual Task Edit_single_property_collection_of_uint32() async context => { var result = await context.Set().SingleAsync(x => x.Id == 1); - Assert.Equal(new[] { 1237775789U }, result.Reference.TestUnsignedInt32Collection); + Assert.Equal(new[] { 1237775789U }, result.Reference!.TestUnsignedInt32Collection); Assert.Equal(new[] { 1237775789U }, result.Collection[0].TestUnsignedInt32Collection); Assert.False(result.Reference.NewCollectionSet); @@ -2223,7 +2221,7 @@ public virtual Task Edit_single_property_collection_of_uint64() { var query = await context.JsonEntitiesAllTypes.ToListAsync(); var entity = query.Single(x => x.Id == 1); - entity.Reference.TestUnsignedInt64Collection = [1234555555123456789UL]; + entity.Reference!.TestUnsignedInt64Collection = [1234555555123456789UL]; entity.Collection[0].TestUnsignedInt64Collection = [1234555555123456789UL]; ClearLog(); @@ -2232,7 +2230,7 @@ public virtual Task Edit_single_property_collection_of_uint64() async context => { var result = await context.Set().SingleAsync(x => x.Id == 1); - Assert.Equal(new[] { 1234555555123456789UL }, result.Reference.TestUnsignedInt64Collection); + Assert.Equal(new[] { 1234555555123456789UL }, result.Reference!.TestUnsignedInt64Collection); Assert.Equal(new[] { 1234555555123456789UL }, result.Collection[0].TestUnsignedInt64Collection); Assert.False(result.Reference.NewCollectionSet); @@ -2248,7 +2246,7 @@ public virtual Task Edit_single_property_collection_of_nullable_int32() { var query = await context.JsonEntitiesAllTypes.ToListAsync(); var entity = query.Single(x => x.Id == 1); - entity.Reference.TestNullableInt32Collection.Add(77); + entity.Reference!.TestNullableInt32Collection!.Add(77); entity.Reference.TestNullableInt32Collection.Add(null); entity.Collection[0].TestNullableInt32Collection = [null, 77]; @@ -2259,7 +2257,7 @@ public virtual Task Edit_single_property_collection_of_nullable_int32() { var result = await context.Set().SingleAsync(x => x.Id == 1); Assert.Equal( - new int?[] { null, int.MinValue, 0, null, int.MaxValue, null, 77, null }, result.Reference.TestNullableInt32Collection); + new int?[] { null, int.MinValue, 0, null, int.MaxValue, null, 77, null }, result.Reference!.TestNullableInt32Collection); Assert.Equal(new int?[] { null, 77 }, result.Collection[0].TestNullableInt32Collection); Assert.False(result.Reference.NewCollectionSet); @@ -2275,7 +2273,7 @@ public virtual Task Edit_single_property_collection_of_nullable_int32_set_to_nul { var query = await context.JsonEntitiesAllTypes.ToListAsync(); var entity = query.Single(x => x.Id == 1); - entity.Reference.TestNullableInt32Collection = null; + entity.Reference!.TestNullableInt32Collection = null; entity.Collection[0].TestNullableInt32Collection = null; ClearLog(); @@ -2284,7 +2282,7 @@ public virtual Task Edit_single_property_collection_of_nullable_int32_set_to_nul async context => { var result = await context.Set().SingleAsync(x => x.Id == 1); - Assert.Null(result.Reference.TestNullableInt32Collection); + Assert.Null(result.Reference!.TestNullableInt32Collection); Assert.Null(result.Collection[0].TestNullableInt32Collection); Assert.True(result.Reference.NewCollectionSet); // Set to null. @@ -2300,7 +2298,7 @@ public virtual Task Edit_single_property_collection_of_enum() { var query = await context.JsonEntitiesAllTypes.ToListAsync(); var entity = query.Single(x => x.Id == 1); - entity.Reference.TestEnumCollection = [JsonEnum.Three]; + entity.Reference!.TestEnumCollection = [JsonEnum.Three]; entity.Collection[0].TestEnumCollection = [JsonEnum.Three]; ClearLog(); @@ -2309,7 +2307,7 @@ public virtual Task Edit_single_property_collection_of_enum() async context => { var result = await context.Set().SingleAsync(x => x.Id == 1); - Assert.Equal([JsonEnum.Three], result.Reference.TestEnumCollection); + Assert.Equal([JsonEnum.Three], result.Reference!.TestEnumCollection); Assert.Equal([JsonEnum.Three], result.Collection[0].TestEnumCollection); Assert.False(result.Reference.NewCollectionSet); @@ -2325,7 +2323,7 @@ public virtual Task Edit_single_property_collection_of_enum_with_int_converter() { var query = await context.JsonEntitiesAllTypes.ToListAsync(); var entity = query.Single(x => x.Id == 1); - entity.Reference.TestEnumWithIntConverterCollection = [JsonEnum.Three]; + entity.Reference!.TestEnumWithIntConverterCollection = [JsonEnum.Three]; entity.Collection[0].TestEnumWithIntConverterCollection = [JsonEnum.Three]; ClearLog(); @@ -2334,7 +2332,7 @@ public virtual Task Edit_single_property_collection_of_enum_with_int_converter() async context => { var result = await context.Set().SingleAsync(x => x.Id == 1); - Assert.Equal([JsonEnum.Three], result.Reference.TestEnumWithIntConverterCollection); + Assert.Equal([JsonEnum.Three], result.Reference!.TestEnumWithIntConverterCollection); Assert.Equal([JsonEnum.Three], result.Collection[0].TestEnumWithIntConverterCollection); Assert.False(result.Reference.NewCollectionSet); @@ -2350,7 +2348,7 @@ public virtual Task Edit_single_property_collection_of_nullable_enum() { var query = await context.JsonEntitiesAllTypes.ToListAsync(); var entity = query.Single(x => x.Id == 1); - entity.Reference.TestEnumCollection = [JsonEnum.Three]; + entity.Reference!.TestEnumCollection = [JsonEnum.Three]; entity.Collection[0].TestEnumCollection = [JsonEnum.Three]; ClearLog(); @@ -2359,7 +2357,7 @@ public virtual Task Edit_single_property_collection_of_nullable_enum() async context => { var result = await context.Set().SingleAsync(x => x.Id == 1); - Assert.Equal([JsonEnum.Three], result.Reference.TestEnumCollection); + Assert.Equal([JsonEnum.Three], result.Reference!.TestEnumCollection); Assert.Equal([JsonEnum.Three], result.Collection[0].TestEnumCollection); Assert.False(result.Reference.NewCollectionSet); @@ -2375,7 +2373,7 @@ public virtual Task Edit_single_property_collection_of_nullable_enum_set_to_null { var query = await context.JsonEntitiesAllTypes.ToListAsync(); var entity = query.Single(x => x.Id == 1); - entity.Reference.TestNullableEnumCollection = null; + entity.Reference!.TestNullableEnumCollection = null; entity.Collection[0].TestNullableEnumCollection = null; ClearLog(); @@ -2384,7 +2382,7 @@ public virtual Task Edit_single_property_collection_of_nullable_enum_set_to_null async context => { var result = await context.Set().SingleAsync(x => x.Id == 1); - Assert.Null(result.Reference.TestNullableEnumCollection); + Assert.Null(result.Reference!.TestNullableEnumCollection); Assert.Null(result.Collection[0].TestNullableEnumCollection); Assert.True(result.Reference.NewCollectionSet); // Set to null. @@ -2400,10 +2398,10 @@ public virtual Task Edit_single_property_collection_of_nullable_enum_with_int_co { var query = await context.JsonEntitiesAllTypes.ToListAsync(); var entity = query.Single(x => x.Id == 1); - entity.Reference.TestNullableEnumWithIntConverterCollection.Add(JsonEnum.Two); - entity.Reference.TestNullableEnumWithIntConverterCollection.RemoveAt(1); - entity.Collection[0].TestNullableEnumWithIntConverterCollection.Add(JsonEnum.Two); - entity.Collection[0].TestNullableEnumWithIntConverterCollection.RemoveAt(2); + entity.Reference!.TestNullableEnumWithIntConverterCollection!.Add(JsonEnum.Two); + entity.Reference.TestNullableEnumWithIntConverterCollection!.RemoveAt(1); + entity.Collection[0].TestNullableEnumWithIntConverterCollection!.Add(JsonEnum.Two); + entity.Collection[0].TestNullableEnumWithIntConverterCollection!.RemoveAt(2); ClearLog(); await context.SaveChangesAsync(); @@ -2413,7 +2411,7 @@ public virtual Task Edit_single_property_collection_of_nullable_enum_with_int_co var result = await context.Set().SingleAsync(x => x.Id == 1); Assert.Equal( new JsonEnum?[] { JsonEnum.One, JsonEnum.Three, (JsonEnum)(-7), JsonEnum.Two }, - result.Reference.TestNullableEnumWithIntConverterCollection); + result.Reference!.TestNullableEnumWithIntConverterCollection); Assert.Equal( new JsonEnum?[] { JsonEnum.One, null, (JsonEnum)(-7), JsonEnum.Two }, result.Collection[0].TestNullableEnumWithIntConverterCollection); @@ -2431,7 +2429,7 @@ public virtual Task Edit_single_property_collection_of_nullable_enum_with_int_co { var query = await context.JsonEntitiesAllTypes.ToListAsync(); var entity = query.Single(x => x.Id == 1); - entity.Reference.TestNullableEnumWithIntConverterCollection = null; + entity.Reference!.TestNullableEnumWithIntConverterCollection = null; entity.Collection[0].TestNullableEnumWithIntConverterCollection = null; ClearLog(); @@ -2440,7 +2438,7 @@ public virtual Task Edit_single_property_collection_of_nullable_enum_with_int_co async context => { var result = await context.Set().SingleAsync(x => x.Id == 1); - Assert.Null(result.Reference.TestNullableEnumWithIntConverterCollection); + Assert.Null(result.Reference!.TestNullableEnumWithIntConverterCollection); Assert.Null(result.Collection[0].TestNullableEnumWithIntConverterCollection); Assert.True(result.Reference.NewCollectionSet); // Set to null. @@ -2456,7 +2454,7 @@ public virtual Task Edit_single_property_collection_of_nullable_enum_with_conver { var query = await context.JsonEntitiesAllTypes.ToListAsync(); var entity = query.Single(x => x.Id == 1); - entity.Reference.TestNullableEnumWithConverterThatHandlesNullsCollection = [JsonEnum.One]; + entity.Reference!.TestNullableEnumWithConverterThatHandlesNullsCollection = [JsonEnum.One]; entity.Collection[0].TestNullableEnumWithConverterThatHandlesNullsCollection = [JsonEnum.Three]; ClearLog(); @@ -2465,7 +2463,7 @@ public virtual Task Edit_single_property_collection_of_nullable_enum_with_conver async context => { var result = await context.Set().SingleAsync(x => x.Id == 1); - Assert.Equal([JsonEnum.One], result.Reference.TestNullableEnumWithConverterThatHandlesNullsCollection); + Assert.Equal([JsonEnum.One], result.Reference!.TestNullableEnumWithConverterThatHandlesNullsCollection); Assert.Equal( [JsonEnum.Three], result.Collection[0].TestNullableEnumWithConverterThatHandlesNullsCollection); @@ -2482,7 +2480,7 @@ public virtual Task Edit_single_property_collection_of_nullable_enum_with_conver { var query = await context.JsonEntitiesAllTypes.ToListAsync(); var entity = query.Single(x => x.Id == 1); - entity.Reference.TestNullableEnumWithConverterThatHandlesNullsCollection = null; + entity.Reference!.TestNullableEnumWithConverterThatHandlesNullsCollection = null; entity.Collection[0].TestNullableEnumWithConverterThatHandlesNullsCollection = null; ClearLog(); @@ -2491,7 +2489,7 @@ public virtual Task Edit_single_property_collection_of_nullable_enum_with_conver async context => { var result = await context.Set().SingleAsync(x => x.Id == 1); - Assert.Null(result.Reference.TestNullableEnumWithConverterThatHandlesNullsCollection); + Assert.Null(result.Reference!.TestNullableEnumWithConverterThatHandlesNullsCollection); Assert.Null(result.Collection[0].TestNullableEnumWithConverterThatHandlesNullsCollection); Assert.False(result.Reference.NewCollectionSet); @@ -2583,7 +2581,7 @@ public virtual Task Edit_single_property_relational_collection_of_datetime() { var query = await context.JsonEntitiesAllTypes.ToListAsync(); var entity = query.Single(x => x.Id == 1); - entity.TestDateTimeCollection.Add(DateTime.Parse("01/01/3000 12:34:56")); + entity.TestDateTimeCollection!.Add(DateTime.Parse("01/01/3000 12:34:56")); ClearLog(); await context.SaveChangesAsync(); @@ -2660,7 +2658,7 @@ public virtual Task Edit_single_property_relational_collection_of_double() { var query = await context.JsonEntitiesAllTypes.ToListAsync(); var entity = query.Single(x => x.Id == 1); - entity.TestDoubleCollection.Add(-1.23579); + entity.TestDoubleCollection!.Add(-1.23579); ClearLog(); await context.SaveChangesAsync(); @@ -2756,6 +2754,7 @@ public virtual Task Edit_single_property_relational_collection_of_int64() async context => { var result = await context.Set().SingleAsync(x => x.Id == 1); + Check.DebugAssert(result.TestInt64Collection != null); Assert.Empty(result.TestInt64Collection); Assert.False(result.NewCollectionSet); @@ -2814,7 +2813,7 @@ public virtual Task Edit_single_property_relational_collection_of_timespan() { var query = await context.JsonEntitiesAllTypes.ToListAsync(); var entity = query.Single(x => x.Id == 1); - entity.TestTimeSpanCollection[0] = new TimeSpan(0, 10, 1, 1, 7); + entity.TestTimeSpanCollection![0] = new TimeSpan(0, 10, 1, 1, 7); ClearLog(); await context.SaveChangesAsync(); @@ -2903,7 +2902,7 @@ public virtual Task Edit_single_property_relational_collection_of_nullable_int32 { var query = await context.JsonEntitiesAllTypes.ToListAsync(); var entity = query.Single(x => x.Id == 1); - entity.TestNullableInt32Collection.Add(77); + entity.TestNullableInt32Collection!.Add(77); entity.TestNullableInt32Collection.Add(null); ClearLog(); @@ -3037,7 +3036,7 @@ public virtual Task Edit_single_property_relational_collection_of_nullable_enum_ { var query = await context.JsonEntitiesAllTypes.ToListAsync(); var entity = query.Single(x => x.Id == 1); - entity.TestNullableEnumWithIntConverterCollection.Add(JsonEnum.Two); + entity.TestNullableEnumWithIntConverterCollection!.Add(JsonEnum.Two); entity.TestNullableEnumWithIntConverterCollection.RemoveAt(1); ClearLog(); @@ -3132,7 +3131,7 @@ public virtual Task Edit_single_property_collection_of_collection_of_bool() { var query = await context.JsonEntitiesAllTypes.ToListAsync(); var entity = query.Single(x => x.Id == 1); - entity.Reference.TestBooleanCollectionCollection = expected1; + entity.Reference!.TestBooleanCollectionCollection = expected1; entity.Collection[0].TestBooleanCollectionCollection = expected2; ClearLog(); @@ -3141,7 +3140,7 @@ public virtual Task Edit_single_property_collection_of_collection_of_bool() async context => { var result = await context.Set().SingleAsync(x => x.Id == 1); - Assert.Equal(expected1, result.Reference.TestBooleanCollectionCollection); + Assert.Equal(expected1, result.Reference!.TestBooleanCollectionCollection); Assert.Equal(expected2, result.Collection[0].TestBooleanCollectionCollection); }); } @@ -3155,7 +3154,7 @@ public virtual Task Edit_single_property_collection_of_collection_of_char() { var query = await context.JsonEntitiesAllTypes.ToListAsync(); var entity = query.Single(x => x.Id == 1); - entity.Reference.TestCharacterCollectionCollection[0] = + entity.Reference!.TestCharacterCollectionCollection[0] = ['E', 'F', 'C', 'ö', 'r', 'E', '\"', '\\']; entity.Collection[0].TestCharacterCollectionCollection[2] = ['D', 'E', 'F', '\0']; @@ -3167,7 +3166,7 @@ public virtual Task Edit_single_property_collection_of_collection_of_char() var result = await context.Set().SingleAsync(x => x.Id == 1); Assert.Equal( [['E', 'F', 'C', 'ö', 'r', 'E', '\"', '\\'], null, ['D', 'E', 'F']], - result.Reference.TestCharacterCollectionCollection); + result.Reference!.TestCharacterCollectionCollection); Assert.Equal([['A', 'B', 'C'], null, ['D', 'E', 'F', '\0']], result.Collection[0].TestCharacterCollectionCollection); }); @@ -3180,7 +3179,7 @@ public virtual Task Edit_single_property_collection_of_collection_of_double() { var query = await context.JsonEntitiesAllTypes.ToListAsync(); var entity = query.Single(x => x.Id == 1); - entity.Reference.TestDoubleCollectionCollection[0][1] = -3.23579; + entity.Reference!.TestDoubleCollectionCollection[0]![1] = -3.23579; entity.Reference.TestDoubleCollectionCollection[2] = null; entity.Collection[0].TestDoubleCollectionCollection[1] = [-3.23579]; @@ -3190,7 +3189,7 @@ public virtual Task Edit_single_property_collection_of_collection_of_double() async context => { var result = await context.Set().SingleAsync(x => x.Id == 1); - Assert.Equal([[-1.23456789, -3.23579], null, null], result.Reference.TestDoubleCollectionCollection); + Assert.Equal([[-1.23456789, -3.23579], null, null], result.Reference!.TestDoubleCollectionCollection); Assert.Equal([[-1.23456789, -1.23456789], [-3.23579], [1.23456789]], result.Collection[0].TestDoubleCollectionCollection); }); @@ -3203,7 +3202,7 @@ public virtual Task Edit_single_property_collection_of_collection_of_int16() { var query = await context.JsonEntitiesAllTypes.ToListAsync(); var entity = query.Single(x => x.Id == 1); - entity.Reference.TestInt16CollectionCollection[2] = [short.MinValue, 0, short.MaxValue, 3234]; + entity.Reference!.TestInt16CollectionCollection[2] = [short.MinValue, 0, short.MaxValue, 3234]; entity.Collection[0].TestInt16CollectionCollection.Add(null); ClearLog(); @@ -3214,7 +3213,7 @@ public virtual Task Edit_single_property_collection_of_collection_of_int16() var result = await context.Set().SingleAsync(x => x.Id == 1); Assert.Equal( [[short.MinValue, 0, short.MaxValue], null, [short.MinValue, 0, short.MaxValue, 3234]], - result.Reference.TestInt16CollectionCollection); + result.Reference!.TestInt16CollectionCollection); Assert.Equal( [[short.MinValue, 0, short.MaxValue], null, [short.MinValue, 0, short.MaxValue], null], result.Collection[0].TestInt16CollectionCollection); @@ -3229,7 +3228,7 @@ public virtual Task Edit_single_property_collection_of_collection_of_int32() { var query = await context.JsonEntitiesAllTypes.ToListAsync(); var entity = query.Single(x => x.Id == 1); - entity.Reference.TestInt32CollectionCollection[0] = [-3234]; + entity.Reference!.TestInt32CollectionCollection[0] = [-3234]; entity.Collection[0].TestInt32CollectionCollection[2] = [-3234]; ClearLog(); @@ -3238,7 +3237,7 @@ public virtual Task Edit_single_property_collection_of_collection_of_int32() async context => { var result = await context.Set().SingleAsync(x => x.Id == 1); - Assert.Equal([[-3234], null, [int.MinValue, 0, int.MaxValue]], result.Reference.TestInt32CollectionCollection); + Assert.Equal([[-3234], null, [int.MinValue, 0, int.MaxValue]], result.Reference!.TestInt32CollectionCollection); Assert.Equal([[int.MinValue, 0, int.MaxValue], null, [-3234]], result.Collection[0].TestInt32CollectionCollection); }); @@ -3251,7 +3250,7 @@ public virtual Task Edit_single_property_collection_of_collection_of_int64() { var query = await context.JsonEntitiesAllTypes.ToListAsync(); var entity = query.Single(x => x.Id == 1); - entity.Reference.TestInt64CollectionCollection.Clear(); + entity.Reference!.TestInt64CollectionCollection.Clear(); entity.Collection[0].TestInt64CollectionCollection.Clear(); ClearLog(); @@ -3260,7 +3259,7 @@ public virtual Task Edit_single_property_collection_of_collection_of_int64() async context => { var result = await context.Set().SingleAsync(x => x.Id == 1); - Assert.Empty(result.Reference.TestInt64CollectionCollection); + Assert.Empty(result.Reference!.TestInt64CollectionCollection); Assert.Empty(result.Collection[0].TestInt64CollectionCollection); }); @@ -3273,7 +3272,7 @@ public virtual Task Edit_single_property_collection_of_collection_of_single() { var query = await context.JsonEntitiesAllTypes.ToListAsync(); var entity = query.Single(x => x.Id == 1); - entity.Reference.TestSingleCollectionCollection.RemoveAt(0); + entity.Reference!.TestSingleCollectionCollection.RemoveAt(0); entity.Collection[0].TestSingleCollectionCollection.RemoveAt(1); ClearLog(); @@ -3282,7 +3281,7 @@ public virtual Task Edit_single_property_collection_of_collection_of_single() async context => { var result = await context.Set().SingleAsync(x => x.Id == 1); - Assert.Equal([null, [-1.234F, 0.0F, -1.234F]], result.Reference.TestSingleCollectionCollection); + Assert.Equal([null, [-1.234F, 0.0F, -1.234F]], result.Reference!.TestSingleCollectionCollection); Assert.Equal([[-1.234F, 0.0F, -1.234F], [-1.234F, 0.0F, -1.234F]], result.Collection[0].TestSingleCollectionCollection); Assert.False(result.Reference.NewCollectionSet); @@ -3298,7 +3297,7 @@ public virtual Task Edit_single_property_collection_of_collection_of_nullable_in { var query = await context.JsonEntitiesAllTypes.ToListAsync(); var entity = query.Single(x => x.Id == 1); - entity.Reference.TestNullableInt32CollectionCollection[0] = [77]; + entity.Reference!.TestNullableInt32CollectionCollection[0] = [77]; entity.Reference.TestNullableInt32CollectionCollection.Add(null); entity.Collection[0].TestNullableInt32CollectionCollection.Add([null, 77]); @@ -3310,7 +3309,7 @@ public virtual Task Edit_single_property_collection_of_collection_of_nullable_in var result = await context.Set().SingleAsync(x => x.Id == 1); Assert.Equal( [[77], [int.MinValue, null, int.MaxValue, null], null, [int.MinValue, 0, int.MaxValue], null], - result.Reference.TestNullableInt32CollectionCollection); + result.Reference!.TestNullableInt32CollectionCollection); Assert.Equal( [null, [int.MinValue, null, int.MaxValue, null], null, [int.MinValue, 0, int.MaxValue], [null, 77]], result.Collection[0].TestNullableInt32CollectionCollection); @@ -3325,8 +3324,8 @@ public virtual Task Edit_single_property_collection_of_collection_of_nullable_in { var query = await context.JsonEntitiesAllTypes.ToListAsync(); var entity = query.Single(x => x.Id == 1); - entity.Reference.TestNullableInt32CollectionCollection = null; - entity.Collection[0].TestNullableInt32CollectionCollection = null; + entity.Reference!.TestNullableInt32CollectionCollection = null!; + entity.Collection[0].TestNullableInt32CollectionCollection = null!; ClearLog(); await context.SaveChangesAsync(); @@ -3334,7 +3333,7 @@ public virtual Task Edit_single_property_collection_of_collection_of_nullable_in async context => { var result = await context.Set().SingleAsync(x => x.Id == 1); - Assert.Null(result.Reference.TestNullableInt32CollectionCollection); + Assert.Null(result.Reference!.TestNullableInt32CollectionCollection); Assert.Null(result.Collection[0].TestNullableInt32CollectionCollection); }); @@ -3347,8 +3346,8 @@ public virtual Task Edit_single_property_collection_of_collection_of_nullable_en { var query = await context.JsonEntitiesAllTypes.ToListAsync(); var entity = query.Single(x => x.Id == 1); - entity.Reference.TestNullableEnumCollectionCollection = null; - entity.Collection[0].TestNullableEnumCollectionCollection = null; + entity.Reference!.TestNullableEnumCollectionCollection = null!; + entity.Collection[0].TestNullableEnumCollectionCollection = null!; ClearLog(); await context.SaveChangesAsync(); @@ -3356,7 +3355,7 @@ public virtual Task Edit_single_property_collection_of_collection_of_nullable_en async context => { var result = await context.Set().SingleAsync(x => x.Id == 1); - Assert.Null(result.Reference.TestNullableEnumCollectionCollection); + Assert.Null(result.Reference!.TestNullableEnumCollectionCollection); Assert.Null(result.Collection[0].TestNullableEnumCollectionCollection); }); @@ -3369,8 +3368,8 @@ public virtual Task Edit_single_property_collection_of_collection_of_nullable_en { var query = await context.JsonEntitiesAllTypes.ToListAsync(); var entity = query.Single(x => x.Id == 1); - entity.Reference.TestNullableEnumWithIntConverterCollectionCollection[0][1][1] = JsonEnum.Two; - entity.Reference.TestNullableEnumWithIntConverterCollectionCollection[0][1] = [JsonEnum.Two, null]; + entity.Reference!.TestNullableEnumWithIntConverterCollectionCollection[0]![1]![1] = JsonEnum.Two; + entity.Reference.TestNullableEnumWithIntConverterCollectionCollection[0]![1] = [JsonEnum.Two, null]; entity.Collection[0].TestNullableEnumWithIntConverterCollectionCollection[0] = [null, [null, null]]; ClearLog(); @@ -3381,7 +3380,7 @@ public virtual Task Edit_single_property_collection_of_collection_of_nullable_en var result = await context.Set().SingleAsync(x => x.Id == 1); Assert.Equal( [[null, [JsonEnum.Two, null], null, [JsonEnum.One, null, JsonEnum.Three, (JsonEnum)(-7)]], null], - result.Reference.TestNullableEnumWithIntConverterCollectionCollection); + result.Reference!.TestNullableEnumWithIntConverterCollectionCollection); Assert.Equal([[null, [null, null]], null], result.Collection[0].TestNullableEnumWithIntConverterCollectionCollection); }); @@ -3401,7 +3400,7 @@ public virtual Task Add_and_update_top_level_optional_owned_collection_to_JSON(b ? value.Value ? [new JsonOwnedRoot()] : [] - : null + : null! }; context.Add(newEntity); @@ -3417,7 +3416,7 @@ public virtual Task Add_and_update_top_level_optional_owned_collection_to_JSON(b if (value.Value) { Assert.Single(newEntity.OwnedCollectionRoot!); - newEntity.OwnedCollectionRoot = null; + newEntity.OwnedCollectionRoot = null!; } else { @@ -3477,7 +3476,7 @@ public virtual Task Add_and_update_nested_optional_owned_collection_to_JSON(bool ? value.Value ? [new JsonOwnedBranch()] : [] - : null + : null! } }; @@ -3494,7 +3493,7 @@ public virtual Task Add_and_update_nested_optional_owned_collection_to_JSON(bool if (value.Value) { Assert.Single(newEntity.OwnedReferenceRoot.OwnedCollectionBranch!); - newEntity.OwnedReferenceRoot.OwnedCollectionBranch = null; + newEntity.OwnedReferenceRoot.OwnedCollectionBranch = null!; } else { @@ -3636,7 +3635,7 @@ public virtual Task Add_and_update_nested_optional_primitive_collection(bool? va else { Assert.Empty(newEntity.Collection!.Single().TestCharacterCollection!); - newEntity.Collection!.Single().TestCharacterCollection.Add('Z'); + newEntity.Collection!.Single().TestCharacterCollection!.Add('Z'); } } else @@ -3664,7 +3663,7 @@ public virtual Task Add_and_update_nested_optional_primitive_collection(bool? va } else { - Assert.Empty(newEntity.Collection!.Single().TestCharacterCollection); + Assert.Empty(newEntity.Collection!.Single().TestCharacterCollection!); } }); @@ -3677,7 +3676,7 @@ public virtual Task Edit_single_property_with_non_ascii_characters() { var query = await context.JsonEntitiesBasic.ToListAsync(); var entity = query.Single(x => x.Id == 1); - entity.OwnedReferenceRoot.OwnedReferenceBranch.OwnedReferenceLeaf.SomethingSomething = "测试1"; + entity.OwnedReferenceRoot.OwnedReferenceBranch!.OwnedReferenceLeaf.SomethingSomething = "测试1"; var newEntity = new JsonEntityBasic { @@ -3709,10 +3708,10 @@ public virtual Task Edit_single_property_with_non_ascii_characters() async context => { var result = await context.Set().SingleAsync(x => x.Id == 3); - Assert.Equal("测试1", result.OwnedReferenceRoot.OwnedReferenceBranch.OwnedReferenceLeaf.SomethingSomething); + Assert.Equal("测试1", result.OwnedReferenceRoot.OwnedReferenceBranch!.OwnedReferenceLeaf.SomethingSomething); result = await context.Set().SingleAsync(x => x.Id == 1); - Assert.Equal("测试1", result.OwnedReferenceRoot.OwnedReferenceBranch.OwnedReferenceLeaf.SomethingSomething); + Assert.Equal("测试1", result.OwnedReferenceRoot.OwnedReferenceBranch!.OwnedReferenceLeaf.SomethingSomething); }); [Fact] @@ -3726,7 +3725,7 @@ public virtual Task Replace_json_reference_root_preserves_nested_owned_entities_ var entity = query.Single(); // Save original leaf value - var originalLeaf = entity.OwnedReferenceRoot.OwnedReferenceBranch.OwnedReferenceLeaf; + var originalLeaf = entity.OwnedReferenceRoot.OwnedReferenceBranch!.OwnedReferenceLeaf; var originalLeafValue = originalLeaf.SomethingSomething; // Replace the owned reference with a new instance that shares nested reference navigations diff --git a/test/EFCore.Relational.Specification.Tests/Update/StoreValueGenerationFixtureBase.cs b/test/EFCore.Relational.Specification.Tests/Update/StoreValueGenerationFixtureBase.cs index 3678679a873..e03dd17df0d 100644 --- a/test/EFCore.Relational.Specification.Tests/Update/StoreValueGenerationFixtureBase.cs +++ b/test/EFCore.Relational.Specification.Tests/Update/StoreValueGenerationFixtureBase.cs @@ -5,8 +5,6 @@ namespace Microsoft.EntityFrameworkCore.Update; -#nullable disable - public abstract class StoreValueGenerationFixtureBase : SharedStoreFixtureBase { protected override string StoreName diff --git a/test/EFCore.Relational.Specification.Tests/Update/StoreValueGenerationTestBase.cs b/test/EFCore.Relational.Specification.Tests/Update/StoreValueGenerationTestBase.cs index 8e141e5c063..8b7845d1816 100644 --- a/test/EFCore.Relational.Specification.Tests/Update/StoreValueGenerationTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/Update/StoreValueGenerationTestBase.cs @@ -5,8 +5,6 @@ namespace Microsoft.EntityFrameworkCore.Update; -#nullable disable - public abstract class StoreValueGenerationTestBase(TFixture fixture) : IClassFixture, IAsyncLifetime where TFixture : StoreValueGenerationFixtureBase { @@ -133,7 +131,7 @@ protected virtual async Task Test( }; StoreValueGenerationData first; - StoreValueGenerationData second; + StoreValueGenerationData? second; switch (firstOperationType) { diff --git a/test/EFCore.Relational.Specification.Tests/Update/StoredProcedureUpdateTestBase.cs b/test/EFCore.Relational.Specification.Tests/Update/StoredProcedureUpdateTestBase.cs index 7e357c8fcbd..518378ae850 100644 --- a/test/EFCore.Relational.Specification.Tests/Update/StoredProcedureUpdateTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/Update/StoredProcedureUpdateTestBase.cs @@ -5,8 +5,6 @@ namespace Microsoft.EntityFrameworkCore.Update; -#nullable disable - public abstract class StoredProcedureUpdateTestBase(NonSharedFixture fixture) : NonSharedModelTestBase(fixture), IClassFixture { @@ -1041,13 +1039,13 @@ protected async Task Non_sproc_followed_by_sproc_commands_in_the_same_batch(bool protected class Entity { public int Id { get; set; } - public string Name { get; set; } + public string? Name { get; set; } } protected class EntityWithAdditionalProperty { public int Id { get; set; } - public string Name { get; set; } + public string? Name { get; set; } public int AdditionalProperty { get; set; } } @@ -1066,7 +1064,7 @@ protected class Child2 : Parent protected class Parent { public int Id { get; set; } - public string Name { get; set; } + public string? Name { get; set; } } private async Task SaveChanges(DbContext context, bool async) diff --git a/test/EFCore.Relational.Specification.Tests/Update/UpdateSqlGeneratorTestBase.cs b/test/EFCore.Relational.Specification.Tests/Update/UpdateSqlGeneratorTestBase.cs index d0301b9fdff..b2f7a6aac15 100644 --- a/test/EFCore.Relational.Specification.Tests/Update/UpdateSqlGeneratorTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/Update/UpdateSqlGeneratorTestBase.cs @@ -7,8 +7,6 @@ // ReSharper disable InconsistentNaming namespace Microsoft.EntityFrameworkCore.Update; -#nullable disable - public abstract class UpdateSqlGeneratorTestBase { [Fact] @@ -247,11 +245,11 @@ protected IModificationCommand CreateInsertCommand(bool identityKey = true, bool var generator = new ParameterNameGenerator(); var duckType = entry.EntityType; - var idProperty = duckType.FindProperty(nameof(Duck.Id)); - var nameProperty = duckType.FindProperty(nameof(Duck.Name)); - var quacksProperty = duckType.FindProperty(nameof(Duck.Quacks)); - var computedProperty = duckType.FindProperty(nameof(Duck.Computed)); - var concurrencyProperty = duckType.FindProperty(nameof(Duck.ConcurrencyToken)); + var idProperty = duckType.FindProperty(nameof(Duck.Id))!; + var nameProperty = duckType.FindProperty(nameof(Duck.Name))!; + var quacksProperty = duckType.FindProperty(nameof(Duck.Quacks))!; + var computedProperty = duckType.FindProperty(nameof(Duck.Computed))!; + var concurrencyProperty = duckType.FindProperty(nameof(Duck.ConcurrencyToken))!; var columnModifications = new[] { @@ -289,11 +287,11 @@ protected IModificationCommand CreateUpdateCommand(bool isComputed = true, bool var generator = new ParameterNameGenerator(); var duckType = entry.EntityType; - var idProperty = duckType.FindProperty(nameof(Duck.Id)); - var nameProperty = duckType.FindProperty(nameof(Duck.Name)); - var quacksProperty = duckType.FindProperty(nameof(Duck.Quacks)); - var computedProperty = duckType.FindProperty(nameof(Duck.Computed)); - var concurrencyProperty = duckType.FindProperty(nameof(Duck.ConcurrencyToken)); + var idProperty = duckType.FindProperty(nameof(Duck.Id))!; + var nameProperty = duckType.FindProperty(nameof(Duck.Name))!; + var quacksProperty = duckType.FindProperty(nameof(Duck.Quacks))!; + var computedProperty = duckType.FindProperty(nameof(Duck.Computed))!; + var concurrencyProperty = duckType.FindProperty(nameof(Duck.ConcurrencyToken))!; var columnModifications = new[] { @@ -325,8 +323,8 @@ protected IModificationCommand CreateDeleteCommand(bool concurrencyToken = true) var generator = new ParameterNameGenerator(); var duckType = entry.EntityType; - var idProperty = duckType.FindProperty(nameof(Duck.Id)); - var concurrencyProperty = duckType.FindProperty(nameof(Duck.ConcurrencyToken)); + var idProperty = duckType.FindProperty(nameof(Duck.Id))!; + var concurrencyProperty = duckType.FindProperty(nameof(Duck.ConcurrencyToken))!; var columnModifications = new[] { @@ -353,10 +351,10 @@ private IModel GetDuckModel() protected class Duck { public int Id { get; set; } - public string Name { get; set; } + public string? Name { get; set; } public int Quacks { get; set; } public Guid Computed { get; set; } - public byte[] ConcurrencyToken { get; set; } + public byte[]? ConcurrencyToken { get; set; } } private IModificationCommand CreateModificationCommand( diff --git a/test/EFCore.Relational.Specification.Tests/Update/UpdatesRelationalTestBase.cs b/test/EFCore.Relational.Specification.Tests/Update/UpdatesRelationalTestBase.cs index 0d0b017efaf..2b3ff990345 100644 --- a/test/EFCore.Relational.Specification.Tests/Update/UpdatesRelationalTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/Update/UpdatesRelationalTestBase.cs @@ -6,8 +6,6 @@ // ReSharper disable InconsistentNaming namespace Microsoft.EntityFrameworkCore.Update; -#nullable disable - public abstract class UpdatesRelationalTestBase(TFixture fixture) : UpdatesTestBase(fixture) where TFixture : UpdatesRelationalTestBase.UpdatesRelationalFixture { @@ -306,9 +304,9 @@ protected override void OnModelCreating(ModelBuilder modelBuilder, DbContext con { base.OnModelCreating(modelBuilder, context); - modelBuilder.Entity().HasBaseType((string)null).ToTable("ProductView"); - modelBuilder.Entity().HasBaseType((string)null).ToView("ProductView").ToTable("ProductTable"); - modelBuilder.Entity().HasBaseType((string)null).ToView("ProductTable"); + modelBuilder.Entity().HasBaseType((string?)null).ToTable("ProductView"); + modelBuilder.Entity().HasBaseType((string?)null).ToView("ProductView").ToTable("ProductTable"); + modelBuilder.Entity().HasBaseType((string?)null).ToView("ProductTable"); modelBuilder.Entity().HasIndex(p => new { p.Name, p.Price }).IsUnique(); diff --git a/test/EFCore.Relational.Tests/DbSetAsTableNameTest.cs b/test/EFCore.Relational.Tests/DbSetAsTableNameTest.cs index 18d20b83e8c..c6346d294e4 100644 --- a/test/EFCore.Relational.Tests/DbSetAsTableNameTest.cs +++ b/test/EFCore.Relational.Tests/DbSetAsTableNameTest.cs @@ -133,29 +133,29 @@ public virtual void DbSet_long_name_uniquely_truncated() protected abstract class SetsContext : DbContext { - public DbSet Cheeses { get; set; } - public DbSet Chocolates { get; set; } - public DbSet Galaxies { get; set; } - public DbSet DairyMilks { get; set; } - public DbSet Apples { get; set; } - public DbSet Triskets { get; set; } - public DbSet WheatThins { get; set; } - public DbSet Food { get; set; } - public DbSet Beverage { get; set; } + public DbSet Cheeses { get; set; } = null!; + public DbSet Chocolates { get; set; } = null!; + public DbSet Galaxies { get; set; } = null!; + public DbSet DairyMilks { get; set; } = null!; + public DbSet Apples { get; set; } = null!; + public DbSet Triskets { get; set; } = null!; + public DbSet WheatThins { get; set; } = null!; + public DbSet Food { get; set; } = null!; + public DbSet Beverage { get; set; } = null!; public DbSet ReallyLongNames12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890A { get; set; - } + } = null!; public DbSet ReallyLongNames12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890B { get; set; - } + } = null!; public DbSet Bovrils => Set("Bovril"); diff --git a/test/EFCore.Relational.Tests/Design/AnnotationCodeGeneratorTest.cs b/test/EFCore.Relational.Tests/Design/AnnotationCodeGeneratorTest.cs index 7975aa2738f..1be02c1ea78 100644 --- a/test/EFCore.Relational.Tests/Design/AnnotationCodeGeneratorTest.cs +++ b/test/EFCore.Relational.Tests/Design/AnnotationCodeGeneratorTest.cs @@ -35,7 +35,7 @@ public void GenerateFluentApi_IProperty_works_with_collation() { var modelBuilder = CreateModelBuilder(); modelBuilder.Entity("Blog", x => x.Property("Name").UseCollation("foo")); - var property = modelBuilder.Model.FindEntityType("Blog").FindProperty("Name"); + var property = modelBuilder.Model.FindEntityType("Blog")!.FindProperty("Name")!; var annotations = property.GetAnnotations().ToDictionary(a => a.Name, a => a); var result = CreateGenerator().GenerateFluentApiCalls((IProperty)property, annotations).Single(); @@ -55,7 +55,7 @@ public void IsForeignKeyExcludedFromMigrations_false_is_handled_by_convention() x.Property("ParentId"); x.HasOne("Blog").WithMany().HasForeignKey("ParentId"); }); - var foreignKey = modelBuilder.Model.FindEntityType("Blog").GetForeignKeys().Single(); + var foreignKey = modelBuilder.Model.FindEntityType("Blog")!.GetForeignKeys().Single(); var annotations = foreignKey.GetAnnotations().ToDictionary(a => a.Name, a => a); CreateGenerator().RemoveAnnotationsHandledByConventions((IForeignKey)foreignKey, annotations); @@ -74,7 +74,7 @@ public void GenerateFluentApi_IForeignKey_works_with_ExcludeForeignKeyFromMigrat x.Property("ParentId"); x.HasOne("Blog").WithMany().HasForeignKey("ParentId").ExcludeForeignKeyFromMigrations(); }); - var foreignKey = modelBuilder.Model.FindEntityType("Blog").GetForeignKeys().Single(); + var foreignKey = modelBuilder.Model.FindEntityType("Blog")!.GetForeignKeys().Single(); var annotations = foreignKey.GetAnnotations().ToDictionary(a => a.Name, a => a); var result = CreateGenerator().GenerateFluentApiCalls((IForeignKey)foreignKey, annotations).Single(); diff --git a/test/EFCore.Relational.Tests/EFCore.Relational.Tests.csproj b/test/EFCore.Relational.Tests/EFCore.Relational.Tests.csproj index a939fb08504..8bba90480a1 100644 --- a/test/EFCore.Relational.Tests/EFCore.Relational.Tests.csproj +++ b/test/EFCore.Relational.Tests/EFCore.Relational.Tests.csproj @@ -4,7 +4,6 @@ $(DefaultNetCoreTargetFramework) Microsoft.EntityFrameworkCore.Relational.Tests Microsoft.EntityFrameworkCore - disable true diff --git a/test/EFCore.Relational.Tests/Extensions/RelationalBuilderExtensionsTest.cs b/test/EFCore.Relational.Tests/Extensions/RelationalBuilderExtensionsTest.cs index 110ee077ad6..1bec6afa570 100644 --- a/test/EFCore.Relational.Tests/Extensions/RelationalBuilderExtensionsTest.cs +++ b/test/EFCore.Relational.Tests/Extensions/RelationalBuilderExtensionsTest.cs @@ -19,7 +19,7 @@ public void Can_set_fixed_length() .Property(e => e.Name) .IsFixedLength(); - var property = modelBuilder.Model.FindEntityType(typeof(Customer)).FindProperty("Name"); + var property = modelBuilder.Model.FindEntityType(typeof(Customer))!.FindProperty("Name")!; Assert.True(property.IsFixedLength()); @@ -41,7 +41,7 @@ public void Can_set_column_name() .Property(e => e.Name) .HasColumnName("Eman"); - var property = modelBuilder.Model.FindEntityType(typeof(Customer)).FindProperty("Name"); + var property = modelBuilder.Model.FindEntityType(typeof(Customer))!.FindProperty("Name")!; Assert.Equal("Name", property.Name); Assert.Equal("Eman", property.GetColumnName()); @@ -57,7 +57,7 @@ public void Can_set_column_type() .Property(e => e.Name) .HasColumnType("nvarchar(42)"); - var property = modelBuilder.Model.FindEntityType(typeof(Customer)).FindProperty("Name"); + var property = modelBuilder.Model.FindEntityType(typeof(Customer))!.FindProperty("Name")!; Assert.Equal("nvarchar(42)", property.GetColumnType()); } @@ -72,7 +72,7 @@ public void Can_set_column_default_expression() .Property(e => e.Name) .HasDefaultValueSql("CherryCoke"); - var property = modelBuilder.Model.FindEntityType(typeof(Customer)).FindProperty("Name"); + var property = modelBuilder.Model.FindEntityType(typeof(Customer))!.FindProperty("Name")!; Assert.Equal("CherryCoke", property.GetDefaultValueSql()); Assert.Equal(ValueGenerated.OnAdd, property.ValueGenerated); @@ -89,7 +89,7 @@ public void Setting_column_default_expression_does_not_modify_explicitly_set_val .ValueGeneratedOnAddOrUpdate() .HasDefaultValueSql("CherryCoke"); - var property = modelBuilder.Model.FindEntityType(typeof(Customer)).FindProperty("Name"); + var property = modelBuilder.Model.FindEntityType(typeof(Customer))!.FindProperty("Name")!; Assert.Equal("CherryCoke", property.GetDefaultValueSql()); Assert.Equal(ValueGenerated.OnAddOrUpdate, property.ValueGenerated); @@ -105,7 +105,7 @@ public void Can_set_column_computed_expression() .Property(e => e.Name) .HasComputedColumnSql("CherryCoke"); - var property = modelBuilder.Model.FindEntityType(typeof(Customer)).FindProperty("Name"); + var property = modelBuilder.Model.FindEntityType(typeof(Customer))!.FindProperty("Name")!; Assert.Equal("CherryCoke", property.GetComputedColumnSql()); Assert.Equal(ValueGenerated.OnAddOrUpdate, property.ValueGenerated); @@ -122,7 +122,7 @@ public void Setting_column_computed_expression_does_not_modify_explicitly_set_va .ValueGeneratedNever() .HasComputedColumnSql("CherryCoke"); - var property = modelBuilder.Model.FindEntityType(typeof(Customer)).FindProperty("Name"); + var property = modelBuilder.Model.FindEntityType(typeof(Customer))!.FindProperty("Name")!; Assert.Equal("CherryCoke", property.GetComputedColumnSql()); Assert.Equal(ValueGenerated.Never, property.ValueGenerated); @@ -139,7 +139,7 @@ public void Can_set_column_default_value() .Property(e => e.Name) .HasDefaultValue(stringValue); - var property = modelBuilder.Model.FindEntityType(typeof(Customer)).FindProperty("Name"); + var property = modelBuilder.Model.FindEntityType(typeof(Customer))!.FindProperty("Name")!; Assert.Equal(stringValue, property.GetDefaultValue()); Assert.Equal(ValueGenerated.OnAdd, property.ValueGenerated); @@ -155,7 +155,7 @@ public void Can_set_column_default_value_implicit_conversion() .Property(e => e.SomeShort) .HasDefaultValue(7); - var property = modelBuilder.Model.FindEntityType(typeof(Customer)).FindProperty("SomeShort"); + var property = modelBuilder.Model.FindEntityType(typeof(Customer))!.FindProperty("SomeShort")!; Assert.Equal((short)7, property.GetDefaultValue()); Assert.Equal(ValueGenerated.OnAdd, property.ValueGenerated); @@ -173,7 +173,7 @@ public void Setting_column_default_value_does_not_modify_explicitly_set_value_ge .ValueGeneratedOnAddOrUpdate() .HasDefaultValue(stringValue); - var property = modelBuilder.Model.FindEntityType(typeof(Customer)).FindProperty("Name"); + var property = modelBuilder.Model.FindEntityType(typeof(Customer))!.FindProperty("Name")!; Assert.Equal(stringValue, property.GetDefaultValue()); Assert.Equal(ValueGenerated.OnAddOrUpdate, property.ValueGenerated); @@ -189,9 +189,9 @@ public void Can_set_column_default_value_of_enum_type() .Property(e => e.EnumValue) .HasDefaultValue(MyEnum.Tue); - var property = modelBuilder.Model.FindEntityType(typeof(Customer)).FindProperty("EnumValue"); + var property = modelBuilder.Model.FindEntityType(typeof(Customer))!.FindProperty("EnumValue")!; - Assert.Equal(typeof(MyEnum), property.GetDefaultValue().GetType()); + Assert.Equal(typeof(MyEnum), property.GetDefaultValue()!.GetType()); Assert.Equal(MyEnum.Tue, property.GetDefaultValue()); Assert.Equal(ValueGenerated.OnAdd, property.ValueGenerated); } @@ -205,8 +205,8 @@ public void Default_alternate_key_name_is_based_on_key_column_names() .Entity() .HasAlternateKey(e => e.Name); - var entityType = modelBuilder.Model.FindEntityType(typeof(Customer)); - var key = entityType.FindKey(entityType.FindProperty(nameof(Customer.Name))); + var entityType = modelBuilder.Model.FindEntityType(typeof(Customer))!; + var key = entityType.FindKey([entityType.FindProperty(nameof(Customer.Name))!])!; Assert.Equal("AK_Customer_Name", key.GetName()); @@ -229,9 +229,9 @@ public void Default_alternate_key_name_is_based_on_key_column_names() public void Can_access_key() { var modelBuilder = CreateBuilder(); - var entityTypeBuilder = modelBuilder.Entity(typeof(Splot), ConfigurationSource.Convention); - var idProperty = entityTypeBuilder.Property(typeof(int), "Id", ConfigurationSource.Convention).Metadata; - var keyBuilder = entityTypeBuilder.HasKey([idProperty.Name], ConfigurationSource.Convention); + var entityTypeBuilder = modelBuilder.Entity(typeof(Splot), ConfigurationSource.Convention)!; + var idProperty = entityTypeBuilder.Property(typeof(int), "Id", ConfigurationSource.Convention)!.Metadata; + var keyBuilder = entityTypeBuilder.HasKey([idProperty.Name], ConfigurationSource.Convention)!; Assert.NotNull(keyBuilder.HasName("Splew")); Assert.Equal("Splew", keyBuilder.Metadata.GetName()); @@ -251,7 +251,7 @@ public void Default_foreign_key_name_is_based_on_fk_column_names() modelBuilder .Entity().HasMany(e => e.Orders).WithOne(e => e.Customer).HasForeignKey(e => e.CustomerId); - var foreignKey = modelBuilder.Model.FindEntityType(typeof(Order)).GetForeignKeys() + var foreignKey = modelBuilder.Model.FindEntityType(typeof(Order))!.GetForeignKeys() .Single(fk => fk.PrincipalEntityType.ClrType == typeof(Customer)); Assert.Equal("FK_Order_Customer_CustomerId", foreignKey.GetConstraintName()); @@ -271,7 +271,7 @@ public void Can_set_foreign_key_name_for_one_to_many() .Entity().HasMany(e => e.Orders).WithOne(e => e.Customer) .HasConstraintName("LemonSupreme"); - var foreignKey = modelBuilder.Model.FindEntityType(typeof(Order)).GetForeignKeys() + var foreignKey = modelBuilder.Model.FindEntityType(typeof(Order))!.GetForeignKeys() .Single(fk => fk.PrincipalEntityType.ClrType == typeof(Customer)); Assert.Equal("LemonSupreme", foreignKey.GetConstraintName()); @@ -293,7 +293,7 @@ public void Can_set_foreign_key_name_for_one_to_many_with_FK_specified() .HasForeignKey(e => e.CustomerId) .HasConstraintName("LemonSupreme"); - var foreignKey = modelBuilder.Model.FindEntityType(typeof(Order)).GetForeignKeys() + var foreignKey = modelBuilder.Model.FindEntityType(typeof(Order))!.GetForeignKeys() .Single(fk => fk.PrincipalEntityType.ClrType == typeof(Customer)); Assert.Equal("LemonSupreme", foreignKey.GetConstraintName()); @@ -308,7 +308,7 @@ public void Can_set_foreign_key_name_for_many_to_one() .Entity().HasOne(e => e.Customer).WithMany(e => e.Orders) .HasConstraintName("LemonSupreme"); - var foreignKey = modelBuilder.Model.FindEntityType(typeof(Order)).GetForeignKeys() + var foreignKey = modelBuilder.Model.FindEntityType(typeof(Order))!.GetForeignKeys() .Single(fk => fk.PrincipalEntityType.ClrType == typeof(Customer)); Assert.Equal("LemonSupreme", foreignKey.GetConstraintName()); @@ -330,7 +330,7 @@ public void Can_set_foreign_key_name_for_many_to_one_with_FK_specified() .HasForeignKey(e => e.CustomerId) .HasConstraintName("LemonSupreme"); - var foreignKey = modelBuilder.Model.FindEntityType(typeof(Order)).GetForeignKeys() + var foreignKey = modelBuilder.Model.FindEntityType(typeof(Order))!.GetForeignKeys() .Single(fk => fk.PrincipalEntityType.ClrType == typeof(Customer)); Assert.Equal("LemonSupreme", foreignKey.GetConstraintName()); @@ -346,7 +346,7 @@ public void Can_set_foreign_key_name_for_one_to_one() .HasPrincipalKey(e => e.OrderId) .HasConstraintName("LemonSupreme"); - var foreignKey = modelBuilder.Model.FindEntityType(typeof(OrderDetails)).GetForeignKeys().Single(); + var foreignKey = modelBuilder.Model.FindEntityType(typeof(OrderDetails))!.GetForeignKeys().Single(); Assert.Equal("LemonSupreme", foreignKey.GetConstraintName()); @@ -367,7 +367,7 @@ public void Can_set_foreign_key_name_for_one_to_one_with_FK_specified() .HasForeignKey(e => e.Id) .HasConstraintName("LemonSupreme"); - var foreignKey = modelBuilder.Model.FindEntityType(typeof(OrderDetails)).GetForeignKeys().Single(); + var foreignKey = modelBuilder.Model.FindEntityType(typeof(OrderDetails))!.GetForeignKeys().Single(); Assert.Equal("LemonSupreme", foreignKey.GetConstraintName()); } @@ -376,9 +376,9 @@ public void Can_set_foreign_key_name_for_one_to_one_with_FK_specified() public void Can_access_index() { var modelBuilder = CreateBuilder(); - var entityTypeBuilder = modelBuilder.Entity(typeof(Splot), ConfigurationSource.Convention); + var entityTypeBuilder = modelBuilder.Entity(typeof(Splot), ConfigurationSource.Convention)!; entityTypeBuilder.Property(typeof(int), "Id", ConfigurationSource.Convention); - var indexBuilder = entityTypeBuilder.HasIndex(["Id"], ConfigurationSource.Convention); + var indexBuilder = entityTypeBuilder.HasIndex(["Id"], ConfigurationSource.Convention)!; Assert.NotNull(indexBuilder.HasFilter("Splew")); Assert.Equal("Splew", indexBuilder.Metadata.GetFilter()); @@ -405,7 +405,7 @@ public void Default_index_database_name_is_based_on_index_column_names() .Entity() .HasIndex(e => e.Id); - var index = modelBuilder.Model.FindEntityType(typeof(Customer)).GetIndexes().Single(); + var index = modelBuilder.Model.FindEntityType(typeof(Customer))!.GetIndexes().Single(); Assert.Equal("IX_Customer_Id", index.GetDatabaseName()); @@ -427,7 +427,7 @@ public void Can_set_index_database_name() .HasIndex(e => e.Id) .HasDatabaseName("Eeeendeeex"); - var index = modelBuilder.Model.FindEntityType(typeof(Customer)).GetIndexes().Single(); + var index = modelBuilder.Model.FindEntityType(typeof(Customer))!.GetIndexes().Single(); Assert.Equal("Eeeendeeex", index.GetDatabaseName()); } @@ -445,14 +445,14 @@ public void Can_write_index_filter_with_where_clauses() Assert.IsType>(returnedBuilder); var model = builder.Model; - var index = model.FindEntityType(typeof(Customer)).GetIndexes().Single(); + var index = model.FindEntityType(typeof(Customer))!.GetIndexes().Single(); Assert.Equal("[Id] % 2 = 0", index.GetFilter()); } [Fact] public void Can_set_table_name() { - var typeBuilder = CreateBuilder().Entity(typeof(Splot), ConfigurationSource.Convention); + var typeBuilder = CreateBuilder().Entity(typeof(Splot), ConfigurationSource.Convention)!; Assert.NotNull(typeBuilder.ToTable("Splew")); Assert.Equal("Splew", typeBuilder.Metadata.GetTableName()); @@ -467,7 +467,7 @@ public void Can_set_table_name() [Fact] public void Can_set_table_name_and_schema() { - var typeBuilder = CreateBuilder().Entity(typeof(Splot), ConfigurationSource.Convention); + var typeBuilder = CreateBuilder().Entity(typeof(Splot), ConfigurationSource.Convention)!; Assert.NotNull(typeBuilder.ToTable("Splew", "1")); Assert.Equal("Splew", typeBuilder.Metadata.GetTableName()); @@ -485,7 +485,7 @@ public void Can_set_table_name_and_schema() [Fact] public void Can_override_existing_schema() { - var typeBuilder = CreateBuilder().Entity(typeof(Splot), ConfigurationSource.Convention); + var typeBuilder = CreateBuilder().Entity(typeof(Splot), ConfigurationSource.Convention)!; typeBuilder.Metadata.SetSchema("Explicit"); @@ -545,7 +545,7 @@ public void Can_create_check_constraint_with_duplicate_name_replaces_existing() [Fact] public void Can_access_check_constraint() { - var typeBuilder = CreateBuilder().Entity(typeof(Splot), ConfigurationSource.Convention); + var typeBuilder = CreateBuilder().Entity(typeof(Splot), ConfigurationSource.Convention)!; IReadOnlyEntityType entityType = typeBuilder.Metadata; Assert.NotNull(typeBuilder.HasCheckConstraint("Splew", "s > p")); @@ -566,12 +566,12 @@ public void Base_check_constraint_overrides_derived_one() { var modelBuilder = CreateBuilder(); - var derivedBuilder = modelBuilder.Entity(typeof(Splow), ConfigurationSource.Convention); + var derivedBuilder = modelBuilder.Entity(typeof(Splow), ConfigurationSource.Convention)!; IReadOnlyEntityType derivedEntityType = derivedBuilder.Metadata; - derivedBuilder.HasBaseType((EntityType)null, ConfigurationSource.DataAnnotation); + derivedBuilder.HasBaseType((EntityType?)null, ConfigurationSource.DataAnnotation); Assert.NotNull( - derivedBuilder.HasCheckConstraint("Splew", "s < p", fromDataAnnotation: true) + derivedBuilder.HasCheckConstraint("Splew", "s < p", fromDataAnnotation: true)! .HasName("CK_Splow", fromDataAnnotation: true)); Assert.Equal("Splew", derivedEntityType.GetCheckConstraints().Single().ModelName); Assert.Equal("s < p", derivedEntityType.GetCheckConstraints().Single().Sql); @@ -585,13 +585,13 @@ public void Base_check_constraint_overrides_derived_one() Assert.Null(derivedBuilder.HasCheckConstraint("Splew", "s > p")); Assert.Equal("s < p", derivedEntityType.GetCheckConstraints().Single().Sql); - var baseBuilder = modelBuilder.Entity(typeof(Splot), ConfigurationSource.DataAnnotation); + var baseBuilder = modelBuilder.Entity(typeof(Splot), ConfigurationSource.DataAnnotation)!; IReadOnlyEntityType baseEntityType = baseBuilder.Metadata; Assert.Null(derivedEntityType.BaseType); Assert.Empty(baseEntityType.GetCheckConstraints()); Assert.NotNull( - baseBuilder.HasCheckConstraint("Splew", "s < p", fromDataAnnotation: true) + baseBuilder.HasCheckConstraint("Splew", "s < p", fromDataAnnotation: true)! .HasName("CK_Splot", fromDataAnnotation: true)); Assert.Equal("Splew", baseEntityType.GetCheckConstraints().Single().ModelName); Assert.Equal("s < p", baseEntityType.GetCheckConstraints().Single().Sql); @@ -600,7 +600,7 @@ public void Base_check_constraint_overrides_derived_one() Assert.NotNull(derivedBuilder.HasBaseType((EntityType)baseEntityType, ConfigurationSource.DataAnnotation)); Assert.Null( - baseBuilder.HasCheckConstraint("Splew", "s < p", fromDataAnnotation: true) + baseBuilder.HasCheckConstraint("Splew", "s < p", fromDataAnnotation: true)! .HasName("CK_Splew")); Assert.Equal("Splew", baseEntityType.GetCheckConstraints().Single().ModelName); Assert.Equal("s < p", baseEntityType.GetCheckConstraints().Single().Sql); @@ -614,23 +614,23 @@ public void Base_check_constraint_overrides_derived_one_after_base_is_set() { var modelBuilder = CreateBuilder(); - var derivedBuilder = modelBuilder.Entity(typeof(Splow), ConfigurationSource.Convention); - Assert.NotNull(derivedBuilder.HasBaseType((string)null, ConfigurationSource.DataAnnotation)); + var derivedBuilder = modelBuilder.Entity(typeof(Splow), ConfigurationSource.Convention)!; + Assert.NotNull(derivedBuilder.HasBaseType((string?)null, ConfigurationSource.DataAnnotation)); IReadOnlyEntityType derivedEntityType = derivedBuilder.Metadata; Assert.NotNull( - derivedBuilder.HasCheckConstraint("Splew", "s < p", fromDataAnnotation: true) + derivedBuilder.HasCheckConstraint("Splew", "s < p", fromDataAnnotation: true)! .HasName("CK_Splow", fromDataAnnotation: true)); Assert.Equal("Splew", derivedEntityType.GetCheckConstraints().Single().ModelName); Assert.Equal("s < p", derivedEntityType.GetCheckConstraints().Single().Sql); Assert.Equal("CK_Splow", derivedEntityType.GetCheckConstraints().Single().Name); - var baseBuilder = modelBuilder.Entity(typeof(Splot), ConfigurationSource.Convention); + var baseBuilder = modelBuilder.Entity(typeof(Splot), ConfigurationSource.Convention)!; IReadOnlyEntityType baseEntityType = baseBuilder.Metadata; Assert.Null(derivedEntityType.BaseType); Assert.NotNull( - baseBuilder.HasCheckConstraint("Splew", "s < p", fromDataAnnotation: true) + baseBuilder.HasCheckConstraint("Splew", "s < p", fromDataAnnotation: true)! .HasName("CK_Splot", fromDataAnnotation: true)); Assert.Equal("Splew", baseEntityType.GetCheckConstraints().Single().ModelName); Assert.Equal("s < p", baseEntityType.GetCheckConstraints().Single().Sql); @@ -639,7 +639,7 @@ public void Base_check_constraint_overrides_derived_one_after_base_is_set() Assert.NotNull(derivedBuilder.HasBaseType((EntityType)baseEntityType, ConfigurationSource.DataAnnotation)); Assert.Null( - baseBuilder.HasCheckConstraint("Splew", "s < p", fromDataAnnotation: true) + baseBuilder.HasCheckConstraint("Splew", "s < p", fromDataAnnotation: true)! .HasName("CK_Splew")); Assert.Equal("Splew", baseEntityType.GetCheckConstraints().Single().ModelName); Assert.Equal("s < p", baseEntityType.GetCheckConstraints().Single().Sql); @@ -691,23 +691,23 @@ public void Can_create_trigger_with_duplicate_name_replaces_existing() [Fact] public void Can_access_trigger() { - var typeBuilder = CreateBuilder().Entity(typeof(Splot), ConfigurationSource.Convention); + var typeBuilder = CreateBuilder().Entity(typeof(Splot), ConfigurationSource.Convention)!; IReadOnlyEntityType entityType = typeBuilder.Metadata; - var trigger = typeBuilder.HasTrigger("Splew", ConfigurationSource.Convention); + var trigger = typeBuilder.HasTrigger("Splew", ConfigurationSource.Convention)!; Assert.NotNull(trigger.HasTableName("Table1")); Assert.NotNull(trigger.HasTableSchema("dbo")); Assert.Equal("Splew", entityType.GetDeclaredTriggers().Single().ModelName); Assert.Equal("Table1", entityType.GetDeclaredTriggers().Single().GetTableName()); Assert.Equal("dbo", entityType.GetDeclaredTriggers().Single().GetTableSchema()); - trigger = typeBuilder.HasTrigger("Splew", ConfigurationSource.DataAnnotation); + trigger = typeBuilder.HasTrigger("Splew", ConfigurationSource.DataAnnotation)!; Assert.NotNull(trigger.HasTableName("Table2", fromDataAnnotation: true)); Assert.NotNull(trigger.HasTableSchema("dbo", fromDataAnnotation: true)); Assert.Equal("Splew", entityType.GetDeclaredTriggers().Single().ModelName); Assert.Equal("Table2", entityType.GetDeclaredTriggers().Single().GetTableName()); - trigger = typeBuilder.HasTrigger("Splew", ConfigurationSource.Convention); + trigger = typeBuilder.HasTrigger("Splew", ConfigurationSource.Convention)!; Assert.Null(trigger.HasTableName("Table1")); Assert.NotNull(trigger.HasTableSchema("dbo")); Assert.Equal("Splew", entityType.GetDeclaredTriggers().Single().ModelName); @@ -725,11 +725,11 @@ public void Can_set_discriminator_value_using_property_expression() .HasValue(typeof(Customer), "1") .HasValue(typeof(SpecialCustomer), "2"); - var entityType = modelBuilder.Model.FindEntityType(typeof(Customer)); - Assert.Equal("Name", entityType.FindDiscriminatorProperty().Name); - Assert.Equal(typeof(string), entityType.FindDiscriminatorProperty().ClrType); + var entityType = modelBuilder.Model.FindEntityType(typeof(Customer))!; + Assert.Equal("Name", entityType.FindDiscriminatorProperty()!.Name); + Assert.Equal(typeof(string), entityType.FindDiscriminatorProperty()!.ClrType); Assert.Equal("1", entityType.GetDiscriminatorValue()); - Assert.Equal("2", modelBuilder.Model.FindEntityType(typeof(SpecialCustomer)).GetDiscriminatorValue()); + Assert.Equal("2", modelBuilder.Model.FindEntityType(typeof(SpecialCustomer))!.GetDiscriminatorValue()); } [Fact] @@ -748,11 +748,11 @@ public void Can_set_discriminator_value_using_property_expression_separately() .HasDiscriminator(b => b.Name) .HasValue("2"); - var entityType = modelBuilder.Model.FindEntityType(typeof(Customer)); - Assert.Equal("Name", entityType.FindDiscriminatorProperty().Name); - Assert.Equal(typeof(string), entityType.FindDiscriminatorProperty().ClrType); + var entityType = modelBuilder.Model.FindEntityType(typeof(Customer))!; + Assert.Equal("Name", entityType.FindDiscriminatorProperty()!.Name); + Assert.Equal(typeof(string), entityType.FindDiscriminatorProperty()!.ClrType); Assert.Equal("1", entityType.GetDiscriminatorValue()); - Assert.Equal("2", modelBuilder.Model.FindEntityType(typeof(SpecialCustomer)).GetDiscriminatorValue()); + Assert.Equal("2", modelBuilder.Model.FindEntityType(typeof(SpecialCustomer))!.GetDiscriminatorValue()); } [Fact] @@ -766,11 +766,11 @@ public void Can_set_discriminator_value_using_property_name() .HasValue(typeof(Customer), "1") .HasValue(typeof(SpecialCustomer), "2"); - var entityType = modelBuilder.Model.FindEntityType(typeof(Customer)); - Assert.Equal("Name", entityType.FindDiscriminatorProperty().Name); - Assert.Equal(typeof(string), entityType.FindDiscriminatorProperty().ClrType); + var entityType = modelBuilder.Model.FindEntityType(typeof(Customer))!; + Assert.Equal("Name", entityType.FindDiscriminatorProperty()!.Name); + Assert.Equal(typeof(string), entityType.FindDiscriminatorProperty()!.ClrType); Assert.Equal("1", entityType.GetDiscriminatorValue()); - Assert.Equal("2", modelBuilder.Model.FindEntityType(typeof(SpecialCustomer)).GetDiscriminatorValue()); + Assert.Equal("2", modelBuilder.Model.FindEntityType(typeof(SpecialCustomer))!.GetDiscriminatorValue()); } [Fact] @@ -789,11 +789,11 @@ public void Can_set_discriminator_value_using_property_name_separately() .HasDiscriminator("Name") .HasValue("2"); - var entityType = modelBuilder.Model.FindEntityType(typeof(Customer)); - Assert.Equal("Name", entityType.FindDiscriminatorProperty().Name); - Assert.Equal(typeof(string), entityType.FindDiscriminatorProperty().ClrType); + var entityType = modelBuilder.Model.FindEntityType(typeof(Customer))!; + Assert.Equal("Name", entityType.FindDiscriminatorProperty()!.Name); + Assert.Equal(typeof(string), entityType.FindDiscriminatorProperty()!.ClrType); Assert.Equal("1", entityType.GetDiscriminatorValue()); - Assert.Equal("2", modelBuilder.Model.FindEntityType(typeof(SpecialCustomer)).GetDiscriminatorValue()); + Assert.Equal("2", modelBuilder.Model.FindEntityType(typeof(SpecialCustomer))!.GetDiscriminatorValue()); } [Fact] @@ -807,11 +807,11 @@ public void Can_set_discriminator_value_non_generic() .HasValue(typeof(Customer), "1") .HasValue(typeof(SpecialCustomer), "2"); - var entityType = modelBuilder.Model.FindEntityType(typeof(Customer)); - Assert.Equal("Name", entityType.FindDiscriminatorProperty().Name); - Assert.Equal(typeof(string), entityType.FindDiscriminatorProperty().ClrType); + var entityType = modelBuilder.Model.FindEntityType(typeof(Customer))!; + Assert.Equal("Name", entityType.FindDiscriminatorProperty()!.Name); + Assert.Equal(typeof(string), entityType.FindDiscriminatorProperty()!.ClrType); Assert.Equal("1", entityType.GetDiscriminatorValue()); - Assert.Equal("2", modelBuilder.Model.FindEntityType(typeof(SpecialCustomer)).GetDiscriminatorValue()); + Assert.Equal("2", modelBuilder.Model.FindEntityType(typeof(SpecialCustomer))!.GetDiscriminatorValue()); } [Fact] @@ -830,11 +830,11 @@ public void Can_set_discriminator_value_non_generic_separately() .HasDiscriminator("Name", typeof(string)) .HasValue(typeof(SpecialCustomer), "2"); - var entityType = modelBuilder.Model.FindEntityType(typeof(Customer)); - Assert.Equal("Name", entityType.FindDiscriminatorProperty().Name); - Assert.Equal(typeof(string), entityType.FindDiscriminatorProperty().ClrType); + var entityType = modelBuilder.Model.FindEntityType(typeof(Customer))!; + Assert.Equal("Name", entityType.FindDiscriminatorProperty()!.Name); + Assert.Equal(typeof(string), entityType.FindDiscriminatorProperty()!.ClrType); Assert.Equal("1", entityType.GetDiscriminatorValue()); - Assert.Equal("2", modelBuilder.Model.FindEntityType(typeof(SpecialCustomer)).GetDiscriminatorValue()); + Assert.Equal("2", modelBuilder.Model.FindEntityType(typeof(SpecialCustomer))!.GetDiscriminatorValue()); } [Fact] @@ -843,16 +843,16 @@ public void Can_set_discriminator_value_shadow_entity() var modelBuilder = CreateConventionModelBuilder(); modelBuilder - .Entity(typeof(Customer).FullName) + .Entity(typeof(Customer).FullName!) .HasDiscriminator("Name", typeof(string)) - .HasValue(typeof(Customer).FullName, "1") - .HasValue(typeof(SpecialCustomer).FullName, "2"); + .HasValue(typeof(Customer).FullName!, "1") + .HasValue(typeof(SpecialCustomer).FullName!, "2"); - var entityType = modelBuilder.Model.FindEntityType(typeof(Customer)); - Assert.Equal("Name", entityType.FindDiscriminatorProperty().Name); - Assert.Equal(typeof(string), entityType.FindDiscriminatorProperty().ClrType); + var entityType = modelBuilder.Model.FindEntityType(typeof(Customer))!; + Assert.Equal("Name", entityType.FindDiscriminatorProperty()!.Name); + Assert.Equal(typeof(string), entityType.FindDiscriminatorProperty()!.ClrType); Assert.Equal("1", entityType.GetDiscriminatorValue()); - Assert.Equal("2", modelBuilder.Model.FindEntityType(typeof(SpecialCustomer)).GetDiscriminatorValue()); + Assert.Equal("2", modelBuilder.Model.FindEntityType(typeof(SpecialCustomer))!.GetDiscriminatorValue()); } [Fact] @@ -866,11 +866,11 @@ public void Can_set_default_discriminator_value() .HasValue(typeof(Customer), "1") .HasValue(typeof(SpecialCustomer), "2"); - var entityType = modelBuilder.Model.FindEntityType(typeof(Customer)); - Assert.Equal("Discriminator", entityType.FindDiscriminatorProperty().Name); - Assert.Equal(typeof(string), entityType.FindDiscriminatorProperty().ClrType); + var entityType = modelBuilder.Model.FindEntityType(typeof(Customer))!; + Assert.Equal("Discriminator", entityType.FindDiscriminatorProperty()!.Name); + Assert.Equal(typeof(string), entityType.FindDiscriminatorProperty()!.ClrType); Assert.Equal("1", entityType.GetDiscriminatorValue()); - Assert.Equal("2", modelBuilder.Model.FindEntityType(typeof(SpecialCustomer)).GetDiscriminatorValue()); + Assert.Equal("2", modelBuilder.Model.FindEntityType(typeof(SpecialCustomer))!.GetDiscriminatorValue()); } [Fact] @@ -888,11 +888,11 @@ public void Can_set_default_discriminator_value_separately() .HasDiscriminator() .HasValue("2"); - var entityType = modelBuilder.Model.FindEntityType(typeof(Customer)); - Assert.Equal("Discriminator", entityType.FindDiscriminatorProperty().Name); - Assert.Equal(typeof(string), entityType.FindDiscriminatorProperty().ClrType); + var entityType = modelBuilder.Model.FindEntityType(typeof(Customer))!; + Assert.Equal("Discriminator", entityType.FindDiscriminatorProperty()!.Name); + Assert.Equal(typeof(string), entityType.FindDiscriminatorProperty()!.ClrType); Assert.Equal("1", entityType.GetDiscriminatorValue()); - Assert.Equal("2", modelBuilder.Model.FindEntityType(typeof(SpecialCustomer)).GetDiscriminatorValue()); + Assert.Equal("2", modelBuilder.Model.FindEntityType(typeof(SpecialCustomer))!.GetDiscriminatorValue()); } [Fact] @@ -950,7 +950,7 @@ public void Model_schema_is_used_if_table_schema_not_set() .Entity() .ToTable("Customizer"); - var entityType = modelBuilder.Model.FindEntityType(typeof(Customer)); + var entityType = modelBuilder.Model.FindEntityType(typeof(Customer))!; Assert.Equal("Customer", entityType.DisplayName()); Assert.Equal("Customizer", entityType.GetTableName()); @@ -974,7 +974,7 @@ public void Model_schema_is_not_used_if_table_schema_is_set() .Entity() .ToTable("Customizer", "db1"); - var entityType = modelBuilder.Model.FindEntityType(typeof(Customer)); + var entityType = modelBuilder.Model.FindEntityType(typeof(Customer))!; Assert.Equal("db0", modelBuilder.Model.GetDefaultSchema()); Assert.Equal("Customer", entityType.DisplayName()); @@ -990,7 +990,7 @@ public void Sequence_is_in_model_schema_if_not_specified_explicitly() modelBuilder.HasDefaultSchema("Tasty"); modelBuilder.HasSequence("Snook"); - var sequence = modelBuilder.Model.FindSequence("Snook"); + var sequence = modelBuilder.Model.FindSequence("Snook")!; Assert.Equal("Tasty", modelBuilder.Model.GetDefaultSchema()); ValidateSchemaNamedSequence(sequence); @@ -1004,7 +1004,7 @@ public void Sequence_is_not_in_model_schema_if_specified_explicitly() modelBuilder.HasDefaultSchema("db0"); modelBuilder.HasSequence("Snook", "Tasty"); - var sequence = modelBuilder.Model.FindSequence("Snook", "Tasty"); + var sequence = modelBuilder.Model.FindSequence("Snook", "Tasty")!; Assert.Equal("db0", modelBuilder.Model.GetDefaultSchema()); ValidateSchemaNamedSequence(sequence); @@ -1017,7 +1017,7 @@ public void Can_create_named_sequence() modelBuilder.HasSequence("Snook"); - var sequence = modelBuilder.Model.FindSequence("Snook"); + var sequence = modelBuilder.Model.FindSequence("Snook")!; ValidateNamedSequence(sequence); } @@ -1040,7 +1040,7 @@ public void Can_create_schema_named_sequence() modelBuilder.HasSequence("Snook", "Tasty"); - var sequence = modelBuilder.Model.FindSequence("Snook", "Tasty"); + var sequence = modelBuilder.Model.FindSequence("Snook", "Tasty")!; ValidateSchemaNamedSequence(sequence); } @@ -1068,7 +1068,7 @@ public void Can_create_named_sequence_with_specific_facets() .HasMin(111) .HasMax(2222); - var sequence = modelBuilder.Model.FindSequence("Snook"); + var sequence = modelBuilder.Model.FindSequence("Snook")!; ValidateNamedSpecificSequence(sequence); } @@ -1085,7 +1085,7 @@ public void Can_create_named_sequence_with_specific_facets_non_generic() .HasMin(111) .HasMax(2222); - var sequence = modelBuilder.Model.FindSequence("Snook"); + var sequence = modelBuilder.Model.FindSequence("Snook")!; ValidateNamedSpecificSequence(sequence); } @@ -1102,7 +1102,7 @@ public void Can_create_named_sequence_with_specific_facets_using_nested_closure( .HasMin(111) .HasMax(2222)); - var sequence = modelBuilder.Model.FindSequence("Snook"); + var sequence = modelBuilder.Model.FindSequence("Snook")!; ValidateNamedSpecificSequence(sequence); } @@ -1119,7 +1119,7 @@ public void Can_create_named_sequence_with_specific_facets_using_nested_closure_ .HasMin(111) .HasMax(2222)); - var sequence = modelBuilder.Model.FindSequence("Snook"); + var sequence = modelBuilder.Model.FindSequence("Snook")!; ValidateNamedSpecificSequence(sequence); } @@ -1147,7 +1147,7 @@ public void Can_create_schema_named_sequence_with_specific_facets() .HasMin(111) .HasMax(2222); - var sequence = modelBuilder.Model.FindSequence("Snook", "Tasty"); + var sequence = modelBuilder.Model.FindSequence("Snook", "Tasty")!; ValidateSchemaNamedSpecificSequence(sequence); } @@ -1164,7 +1164,7 @@ public void Can_create_schema_named_sequence_with_specific_facets_non_generic() .HasMin(111) .HasMax(2222); - var sequence = modelBuilder.Model.FindSequence("Snook", "Tasty"); + var sequence = modelBuilder.Model.FindSequence("Snook", "Tasty")!; ValidateSchemaNamedSpecificSequence(sequence); } @@ -1178,7 +1178,7 @@ public void Can_create_schema_named_sequence_with_specific_facets_using_nested_c .HasSequence( "Snook", "Tasty", b => b.IncrementsBy(11).StartsAt(1729).HasMin(111).HasMax(2222)); - var sequence = modelBuilder.Model.FindSequence("Snook", "Tasty"); + var sequence = modelBuilder.Model.FindSequence("Snook", "Tasty")!; ValidateSchemaNamedSpecificSequence(sequence); } @@ -1193,7 +1193,7 @@ public void Can_create_schema_named_sequence_with_specific_facets_using_nested_c typeof(int), "Snook", "Tasty", b => b.IncrementsBy(11).StartsAt(1729).HasMin(111).HasMax(2222)); - var sequence = modelBuilder.Model.FindSequence("Snook", "Tasty"); + var sequence = modelBuilder.Model.FindSequence("Snook", "Tasty")!; ValidateSchemaNamedSpecificSequence(sequence); } @@ -1201,7 +1201,7 @@ public void Can_create_schema_named_sequence_with_specific_facets_using_nested_c [Fact] public void Can_access_comment() { - var typeBuilder = CreateBuilder().Entity(typeof(Splot), ConfigurationSource.Convention); + var typeBuilder = CreateBuilder().Entity(typeof(Splot), ConfigurationSource.Convention)!; var entityType = typeBuilder.Metadata; Assert.NotNull(typeBuilder.HasComment("My Comment")); @@ -1218,7 +1218,7 @@ public void Can_access_comment() public void Can_create_dbFunction() { var modelBuilder = CreateConventionModelBuilder(); - var testMethod = typeof(RelationalBuilderExtensionsTest).GetTypeInfo().GetDeclaredMethod(nameof(MethodA)); + var testMethod = typeof(RelationalBuilderExtensionsTest).GetTypeInfo().GetDeclaredMethod(nameof(MethodA))!; modelBuilder.HasDbFunction(testMethod); var dbFunc = modelBuilder.Model.FindDbFunction(testMethod) as DbFunction; @@ -1357,8 +1357,8 @@ public void Relational_property_methods_have_non_generic_overloads() public void Can_access_property() { var propertyBuilder = CreateBuilder() - .Entity(typeof(Splot), ConfigurationSource.Convention) - .Property(typeof(int), "Id", ConfigurationSource.Convention); + .Entity(typeof(Splot), ConfigurationSource.Convention)! + .Property(typeof(int), "Id", ConfigurationSource.Convention)!; Assert.NotNull(propertyBuilder.IsFixedLength(true)); Assert.True(propertyBuilder.Metadata.IsFixedLength()); @@ -1448,9 +1448,9 @@ public void Relational_relationship_methods_have_non_generic_overloads() public void Can_access_relationship() { var modelBuilder = CreateBuilder(); - var entityTypeBuilder = modelBuilder.Entity(typeof(Splot), ConfigurationSource.Convention); + var entityTypeBuilder = modelBuilder.Entity(typeof(Splot), ConfigurationSource.Convention)!; entityTypeBuilder.Property(typeof(int), "Id", ConfigurationSource.Convention); - var relationshipBuilder = entityTypeBuilder.HasRelationship("Splot", ["Id"], ConfigurationSource.Convention); + var relationshipBuilder = entityTypeBuilder.HasRelationship("Splot", ["Id"], ConfigurationSource.Convention)!; Assert.NotNull(relationshipBuilder.HasConstraintName("Splew")); Assert.Equal("Splew", relationshipBuilder.Metadata.GetConstraintName()); @@ -1466,9 +1466,9 @@ public void Can_access_relationship() public void Can_access_relationship_ExcludeForeignKeyFromMigrations() { var modelBuilder = CreateBuilder(); - var entityTypeBuilder = modelBuilder.Entity(typeof(Splot), ConfigurationSource.Convention); + var entityTypeBuilder = modelBuilder.Entity(typeof(Splot), ConfigurationSource.Convention)!; entityTypeBuilder.Property(typeof(int), "Id", ConfigurationSource.Convention); - var relationshipBuilder = entityTypeBuilder.HasRelationship("Splot", ["Id"], ConfigurationSource.Convention); + var relationshipBuilder = entityTypeBuilder.HasRelationship("Splot", ["Id"], ConfigurationSource.Convention)!; Assert.NotNull(relationshipBuilder.ExcludeForeignKeyFromMigrations(true)); Assert.True(relationshipBuilder.Metadata.IsExcludedFromMigrations()); @@ -1523,11 +1523,11 @@ private enum MyEnum : ulong private class Customer { public int Id { get; set; } - public string Name { get; set; } + public string Name { get; set; } = null!; public short SomeShort { get; set; } public MyEnum EnumValue { get; set; } - public IEnumerable Orders { get; set; } + public IEnumerable Orders { get; set; } = null!; } private class SpecialCustomer : Customer; @@ -1537,9 +1537,9 @@ private class Order public int OrderId { get; set; } public int CustomerId { get; set; } - public Customer Customer { get; set; } + public Customer Customer { get; set; } = null!; - public OrderDetails Details { get; set; } + public OrderDetails Details { get; set; } = null!; } private class OrderDetails @@ -1547,7 +1547,7 @@ private class OrderDetails public int Id { get; } public int OrderId { get; set; } - public Order Order { get; } + public Order Order { get; } = null!; } private class JsonContainer @@ -1569,7 +1569,7 @@ private class JsonComplex private class Splot { - public static readonly PropertyInfo SplowedProperty = typeof(Splot).GetProperty("Splowed"); + public static readonly PropertyInfo SplowedProperty = typeof(Splot).GetProperty("Splowed")!; public int? Splowed { get; set; } } diff --git a/test/EFCore.Relational.Tests/Extensions/RelationalDatabaseFacadeExtensionsTest.cs b/test/EFCore.Relational.Tests/Extensions/RelationalDatabaseFacadeExtensionsTest.cs index c16e39777c5..67fbb0b1ea1 100644 --- a/test/EFCore.Relational.Tests/Extensions/RelationalDatabaseFacadeExtensionsTest.cs +++ b/test/EFCore.Relational.Tests/Extensions/RelationalDatabaseFacadeExtensionsTest.cs @@ -114,7 +114,7 @@ public void Can_use_transaction() ((FakeRelationalConnection)context.GetService()).UseConnection(dbConnection); var transaction = new FakeDbTransaction(dbConnection, IsolationLevel.Chaos); - Assert.Same(transaction, context.Database.UseTransaction(transaction).GetDbTransaction()); + Assert.Same(transaction, context.Database.UseTransaction(transaction)!.GetDbTransaction()); } [Theory, InlineData(true), InlineData(false)] @@ -175,11 +175,11 @@ public Task CommitTransactionAsync(CancellationToken cancellationToken = default public Task RollbackTransactionAsync(CancellationToken cancellationToken = default) => Task.CompletedTask; - public IDbContextTransaction CurrentTransaction { get; } + public IDbContextTransaction? CurrentTransaction { get; } - public Transaction EnlistedTransaction { get; } + public Transaction? EnlistedTransaction { get; } - public void EnlistTransaction(Transaction transaction) + public void EnlistTransaction(Transaction? transaction) { } } @@ -200,7 +200,7 @@ public void GetMigrations_works() { var migrations = new[] { "00000000000001_One", "00000000000002_Two", "00000000000003_Three" }; - var migrationsAssembly = new FakeIMigrationsAssembly { Migrations = migrations.ToDictionary(x => x, x => default(TypeInfo)) }; + var migrationsAssembly = new FakeIMigrationsAssembly { Migrations = migrations.ToDictionary(x => x, x => default(TypeInfo)!) }; var db = FakeRelationalTestHelpers.Instance.CreateContext( new ServiceCollection().AddSingleton(migrationsAssembly)); @@ -210,9 +210,9 @@ public void GetMigrations_works() private class FakeIMigrationsAssembly : IMigrationsAssembly { - public IReadOnlyDictionary Migrations { get; set; } - public ModelSnapshot ModelSnapshot { get; set; } - public Assembly Assembly { get; } + public IReadOnlyDictionary Migrations { get; set; } = null!; + public ModelSnapshot? ModelSnapshot { get; set; } + public Assembly Assembly { get; } = null!; public string FindMigrationId(string nameOrId) => throw new NotImplementedException(); @@ -294,7 +294,7 @@ public void HasPendingModelChanges_has_migrations_and_no_new_context_changes_ret private class TestDbContext(DbContextOptions options) : DbContext(options) { - public DbSet Simples { get; set; } + public DbSet Simples { get; set; } = null!; public class Simple { @@ -315,7 +315,7 @@ private class FakeHistoryRepository : IHistoryRepository public virtual LockReleaseBehavior LockReleaseBehavior => LockReleaseBehavior.Explicit; - public List AppliedMigrations { get; set; } + public List AppliedMigrations { get; set; } = null!; public IReadOnlyList GetAppliedMigrations() => AppliedMigrations; @@ -370,7 +370,7 @@ public async Task GetPendingMigrations_works(bool async) var appliedMigrations = new[] { "00000000000001_One", "00000000000002_Two" }; - var migrationsAssembly = new FakeIMigrationsAssembly { Migrations = migrations.ToDictionary(x => x, x => default(TypeInfo)) }; + var migrationsAssembly = new FakeIMigrationsAssembly { Migrations = migrations.ToDictionary(x => x, x => default(TypeInfo)!) }; var repository = new FakeHistoryRepository { @@ -614,21 +614,21 @@ private class TestRawSqlCommandBuilder( { private readonly IRelationalCommandBuilderFactory _commandBuilderFactory = relationalCommandBuilderFactory; - public string Sql { get; private set; } - public IEnumerable Parameters { get; private set; } + public string Sql { get; private set; } = null!; + public IEnumerable Parameters { get; private set; } = null!; public IRelationalCommand Build(string sql) => throw new NotImplementedException(); - public RawSqlCommand Build(string sql, IEnumerable parameters) + public RawSqlCommand Build(string sql, IEnumerable parameters) => throw new NotImplementedException(); - public RawSqlCommand Build(string sql, IEnumerable parameters, IModel model) + public RawSqlCommand Build(string sql, IEnumerable parameters, IModel model) { Sql = sql; Parameters = parameters; - return new RawSqlCommand(_commandBuilderFactory.Create().Build(), new Dictionary()); + return new RawSqlCommand(_commandBuilderFactory.Create().Build(), new Dictionary()); } } } diff --git a/test/EFCore.Relational.Tests/Extensions/RelationalMetadataExtensionsTest.cs b/test/EFCore.Relational.Tests/Extensions/RelationalMetadataExtensionsTest.cs index 36efb837885..fefbe33a7c8 100644 --- a/test/EFCore.Relational.Tests/Extensions/RelationalMetadataExtensionsTest.cs +++ b/test/EFCore.Relational.Tests/Extensions/RelationalMetadataExtensionsTest.cs @@ -271,7 +271,7 @@ public void Can_get_and_set_column_default_value_of_enum_type() property.SetDefaultValue(MyEnum.Mon); - Assert.Equal(typeof(MyEnum), property.GetDefaultValue().GetType()); + Assert.Equal(typeof(MyEnum), property.GetDefaultValue()!.GetType()); Assert.Equal(MyEnum.Mon, property.GetDefaultValue()); property.SetDefaultValue(null); @@ -441,7 +441,7 @@ public void Can_get_and_set_schema_name_on_model() [Fact] public void Can_get_and_set_dbfunction() { - var testMethod = typeof(RelationalMetadataExtensionsTest).GetTypeInfo().GetDeclaredMethod(nameof(MethodA)); + var testMethod = typeof(RelationalMetadataExtensionsTest).GetTypeInfo().GetDeclaredMethod(nameof(MethodA))!; var modelBuilder = new ModelBuilder(); var model = modelBuilder.Model; @@ -473,7 +473,7 @@ public void Can_get_and_set_sequence() var sequence = model.AddSequence("Foo"); - Assert.Equal("Foo", model.FindSequence("Foo").Name); + Assert.Equal("Foo", model.FindSequence("Foo")!.Name); Assert.Equal("Foo", sequence.Name); Assert.Null(sequence.Schema); @@ -516,8 +516,8 @@ public void Can_get_and_set_sequence_with_schema_name() var sequence = model.AddSequence("Foo", "Smoo"); - Assert.Equal("Foo", model.FindSequence("Foo", "Smoo").Name); - Assert.Equal("Foo", model.FindSequence("Foo", "Smoo").Name); + Assert.Equal("Foo", model.FindSequence("Foo", "Smoo")!.Name); + Assert.Equal("Foo", model.FindSequence("Foo", "Smoo")!.Name); Assert.Equal("Foo", sequence.Name); Assert.Equal("Smoo", sequence.Schema); @@ -668,7 +668,7 @@ private enum MyEnum : byte private class Customer { public int Id { get; set; } - public string Name { get; set; } + public string Name { get; set; } = null!; public Guid AlternateId { get; set; } public MyEnum? EnumValue { get; set; } } @@ -679,6 +679,6 @@ private class Order { public int OrderId { get; set; } public int CustomerId { get; set; } - public Customer Customer { get; set; } + public Customer Customer { get; set; } = null!; } } diff --git a/test/EFCore.Relational.Tests/Extensions/RelationalTransactionExtensionsTest.cs b/test/EFCore.Relational.Tests/Extensions/RelationalTransactionExtensionsTest.cs index 70be4ecdd0c..6abd4930bd9 100644 --- a/test/EFCore.Relational.Tests/Extensions/RelationalTransactionExtensionsTest.cs +++ b/test/EFCore.Relational.Tests/Extensions/RelationalTransactionExtensionsTest.cs @@ -73,7 +73,7 @@ public ValueTask DisposeAsync() private const string ConnectionString = "Fake Connection String"; public static IDbContextOptions CreateOptions( - FakeRelationalOptionsExtension optionsExtension = null) + FakeRelationalOptionsExtension? optionsExtension = null) { var optionsBuilder = new DbContextOptionsBuilder(); diff --git a/test/EFCore.Relational.Tests/Infrastructure/RelationalEventIdTest.cs b/test/EFCore.Relational.Tests/Infrastructure/RelationalEventIdTest.cs index 805d5f04403..a1d51bfc7b2 100644 --- a/test/EFCore.Relational.Tests/Infrastructure/RelationalEventIdTest.cs +++ b/test/EFCore.Relational.Tests/Infrastructure/RelationalEventIdTest.cs @@ -3,6 +3,7 @@ using System.Collections; using System.Data; +using System.Diagnostics.CodeAnalysis; using System.Transactions; using Microsoft.EntityFrameworkCore.ChangeTracking.Internal; using Microsoft.EntityFrameworkCore.Metadata.Internal; @@ -22,8 +23,8 @@ public void Every_eventId_has_a_logger_method_and_logs_when_level_enabled() var constantExpression = Expression.Constant("A"); var model = new Model(); var entityType = new EntityType(typeof(object), model, owned: false, ConfigurationSource.Convention); - var property = entityType.AddProperty("A", typeof(int), ConfigurationSource.Convention, ConfigurationSource.Convention); - var key = entityType.AddKey(property, ConfigurationSource.Convention); + var property = entityType.AddProperty("A", typeof(int), ConfigurationSource.Convention, ConfigurationSource.Convention)!; + var key = entityType.AddKey(property, ConfigurationSource.Convention)!; var foreignKey = new ForeignKey([property], key, entityType, entityType, ConfigurationSource.Convention); var index = new Index(new List { property }, "IndexName", entityType, ConfigurationSource.Convention); var contextServices = FakeRelationalTestHelpers.Instance.CreateContextServices(model.FinalizeModel()); @@ -59,7 +60,7 @@ public void Every_eventId_has_a_logger_method_and_logs_when_level_enabled() { typeof(Migration), () => new FakeMigration() }, { typeof(IMigrationsAssembly), () => new FakeMigrationsAssembly() }, { typeof(MigrationCommand), () => new FakeMigrationCommand() }, - { typeof(MethodCallExpression), () => Expression.Call(constantExpression, typeof(object).GetMethod("ToString")) }, + { typeof(MethodCallExpression), () => Expression.Call(constantExpression, typeof(object).GetMethod("ToString")!) }, { typeof(Expression), () => constantExpression }, { typeof(IEntityType), () => entityType }, { typeof(IProperty), () => property }, @@ -131,15 +132,15 @@ protected override void Print(ExpressionPrinter expressionPrinter) private class FakeMigrator : IMigrator { - public void Migrate(string targetMigration = null) + public void Migrate(string? targetMigration = null) => throw new NotImplementedException(); - public Task MigrateAsync(string targetMigration = null, CancellationToken cancellationToken = new()) + public Task MigrateAsync(string? targetMigration = null, CancellationToken cancellationToken = new()) => throw new NotImplementedException(); public string GenerateScript( - string fromMigration = null, - string toMigration = null, + string? fromMigration = null, + string? toMigration = null, MigrationsSqlGenerationOptions options = MigrationsSqlGenerationOptions.Default) => throw new NotImplementedException(); @@ -200,7 +201,7 @@ public Task ExecuteReaderAsync( public object ExecuteScalar(RelationalCommandParameterObject parameterObject) => throw new NotImplementedException(); - public Task ExecuteScalarAsync(RelationalCommandParameterObject parameterObject, CancellationToken cancellationToken) + public Task ExecuteScalarAsync(RelationalCommandParameterObject parameterObject, CancellationToken cancellationToken) => throw new NotImplementedException(); public void PopulateFrom(IRelationalCommandTemplate commandTemplate) @@ -209,15 +210,16 @@ public void PopulateFrom(IRelationalCommandTemplate commandTemplate) private class FakeRelationalConnection : IRelationalConnection { - public string ConnectionString { get; set; } + public string? ConnectionString { get; set; } + [AllowNull] public DbConnection DbConnection { get; set; } = new FakeDbConnection(); - public void SetDbConnection(DbConnection value, bool contextOwnsConnection) + public void SetDbConnection(DbConnection? value, bool contextOwnsConnection) => throw new NotImplementedException(); public DbContext Context - => null; + => null!; public Guid ConnectionId => Guid.NewGuid(); @@ -277,19 +279,19 @@ public void RollbackTransaction() public Task RollbackTransactionAsync(CancellationToken cancellationToken = default) => throw new NotImplementedException(); - public IDbContextTransaction UseTransaction(DbTransaction transaction) + public IDbContextTransaction? UseTransaction(DbTransaction? transaction) => throw new NotImplementedException(); - public IDbContextTransaction UseTransaction(DbTransaction transaction, Guid transactionId) + public IDbContextTransaction? UseTransaction(DbTransaction? transaction, Guid transactionId) => throw new NotImplementedException(); - public Task UseTransactionAsync( - DbTransaction transaction, + public Task UseTransactionAsync( + DbTransaction? transaction, CancellationToken cancellationToken = default) => throw new NotImplementedException(); - public Task UseTransactionAsync( - DbTransaction transaction, + public Task UseTransactionAsync( + DbTransaction? transaction, Guid transactionId, CancellationToken cancellationToken = default) => throw new NotImplementedException(); @@ -306,7 +308,8 @@ public void ReturnCommand(IRelationalCommand command) private class FakeDbConnection : DbConnection { - public override string ConnectionString { get; set; } + [AllowNull] + public override string ConnectionString { get; set; } = ""; public override string Database => "Database"; @@ -338,6 +341,7 @@ protected override DbCommand CreateDbCommand() private class FakeDbCommand : DbCommand { + [AllowNull] public override string CommandText { get => "CommandText"; @@ -348,12 +352,12 @@ public override string CommandText public override CommandType CommandType { get; set; } public override bool DesignTimeVisible { get; set; } public override UpdateRowSource UpdatedRowSource { get; set; } - protected override DbConnection DbConnection { get; set; } = new FakeDbConnection(); + protected override DbConnection? DbConnection { get; set; } = new FakeDbConnection(); protected override DbParameterCollection DbParameterCollection => new FakeDbParameterCollection(); - protected override DbTransaction DbTransaction { get; set; } + protected override DbTransaction? DbTransaction { get; set; } public override void Cancel() => throw new NotImplementedException(); @@ -457,13 +461,13 @@ public override bool GetBoolean(int ordinal) public override byte GetByte(int ordinal) => throw new NotImplementedException(); - public override long GetBytes(int ordinal, long dataOffset, byte[] buffer, int bufferOffset, int length) + public override long GetBytes(int ordinal, long dataOffset, byte[]? buffer, int bufferOffset, int length) => throw new NotImplementedException(); public override char GetChar(int ordinal) => throw new NotImplementedException(); - public override long GetChars(int ordinal, long dataOffset, char[] buffer, int bufferOffset, int length) + public override long GetChars(int ordinal, long dataOffset, char[]? buffer, int bufferOffset, int length) => throw new NotImplementedException(); public override string GetDataTypeName(int ordinal) diff --git a/test/EFCore.Relational.Tests/Infrastructure/RelationalModelValidatorTest.Json.cs b/test/EFCore.Relational.Tests/Infrastructure/RelationalModelValidatorTest.Json.cs index 8717afbc03b..07b9ca03109 100644 --- a/test/EFCore.Relational.Tests/Infrastructure/RelationalModelValidatorTest.Json.cs +++ b/test/EFCore.Relational.Tests/Infrastructure/RelationalModelValidatorTest.Json.cs @@ -287,7 +287,7 @@ public void Json_entity_not_mapped_to_table_or_a_view_is_not_supported() var modelBuilder = CreateConventionModelBuilder(); modelBuilder.Entity(b => { - b.ToTable((string)null); + b.ToTable((string?)null); b.OwnsOne( x => x.OwnedReference, bb => { @@ -811,27 +811,27 @@ public void Throws_when_complex_property_scalar_has_both_column_name_and_json_pr protected class ValidatorComplexEntity { public int Id { get; set; } - public ValidatorComplexType ComplexProp { get; set; } + public ValidatorComplexType ComplexProp { get; set; } = null!; } protected class ValidatorComplexType { - public string Name { get; set; } + public string Name { get; set; } = null!; public int Number { get; set; } - public ValidatorNestedComplexType NestedComplex { get; set; } + public ValidatorNestedComplexType NestedComplex { get; set; } = null!; } protected class ValidatorNestedComplexType { - public string Value { get; set; } + public string Value { get; set; } = null!; public int Count { get; set; } } protected class ValidatorJsonEntityBasic { public int Id { get; set; } - public ValidatorJsonOwnedRoot OwnedReference { get; set; } - public List OwnedCollection { get; set; } + public ValidatorJsonOwnedRoot OwnedReference { get; set; } = null!; + public List OwnedCollection { get; set; } = null!; } protected abstract class ValidatorJsonEntityInheritanceAbstract : ValidatorJsonEntityInheritanceBase @@ -842,26 +842,26 @@ protected abstract class ValidatorJsonEntityInheritanceAbstract : ValidatorJsonE protected class ValidatorJsonEntityInheritanceBase { public int Id { get; set; } - public string Name { get; set; } - public ValidatorJsonOwnedBranch ReferenceOnBase { get; set; } + public string Name { get; set; } = null!; + public ValidatorJsonOwnedBranch ReferenceOnBase { get; set; } = null!; } protected class ValidatorJsonEntityInheritanceDerived : ValidatorJsonEntityInheritanceAbstract { public bool Switch { get; set; } - public ValidatorJsonOwnedBranch ReferenceOnDerived { get; set; } + public ValidatorJsonOwnedBranch ReferenceOnDerived { get; set; } = null!; - public List CollectionOnDerived { get; set; } + public List CollectionOnDerived { get; set; } = null!; } protected class ValidatorJsonOwnedRoot { - public string Name { get; set; } + public string Name { get; set; } = null!; public int Number { get; } - public ValidatorJsonOwnedBranch NestedReference { get; } - public List NestedCollection { get; } + public ValidatorJsonOwnedBranch NestedReference { get; } = null!; + public List NestedCollection { get; } = null!; } protected class ValidatorJsonOwnedBranch @@ -873,9 +873,9 @@ protected class ValidatorJsonEntityExplicitOrdinal { public int Id { get; set; } - public string Name { get; set; } + public string Name { get; set; } = null!; - public List OwnedCollection { get; set; } + public List OwnedCollection { get; set; } = null!; } protected class ValidatorJsonOwnedExplicitOrdinal @@ -887,15 +887,15 @@ protected class ValidatorJsonOwnedExplicitOrdinal protected class ValidatorJsonEntityJsonReferencingRegularEntity { public int Id { get; set; } - public ValidatorJsonOwnedReferencingRegularEntity Owned { get; set; } + public ValidatorJsonOwnedReferencingRegularEntity Owned { get; set; } = null!; } protected class ValidatorJsonOwnedReferencingRegularEntity { - public string Foo { get; set; } + public string Foo { get; set; } = null!; public int? Fk { get; } - public ValidatorJsonEntityReferencedEntity Reference { get; } + public ValidatorJsonEntityReferencedEntity Reference { get; } = null!; } protected class ValidatorJsonEntityReferencedEntity @@ -907,17 +907,17 @@ protected class ValidatorJsonEntityReferencedEntity protected class ValidatorJsonEntitySideBySide { public int Id { get; set; } - public string Name { get; set; } - public ValidatorJsonOwnedBranch Reference1 { get; set; } - public ValidatorJsonOwnedBranch Reference2 { get; set; } - public List Collection1 { get; set; } - public List Collection2 { get; set; } + public string Name { get; set; } = null!; + public ValidatorJsonOwnedBranch Reference1 { get; set; } = null!; + public ValidatorJsonOwnedBranch Reference2 { get; set; } = null!; + public List Collection1 { get; set; } = null!; + public List Collection2 { get; set; } = null!; } protected class ValidatorJsonEntityTableSplitting { public int Id { get; set; } - public ValidatorJsonEntityBasic Link { get; set; } + public ValidatorJsonEntityBasic Link { get; set; } = null!; } [Fact] diff --git a/test/EFCore.Relational.Tests/Infrastructure/RelationalModelValidatorTest.cs b/test/EFCore.Relational.Tests/Infrastructure/RelationalModelValidatorTest.cs index 17c17edf6b6..6551cc181b8 100644 --- a/test/EFCore.Relational.Tests/Infrastructure/RelationalModelValidatorTest.cs +++ b/test/EFCore.Relational.Tests/Infrastructure/RelationalModelValidatorTest.cs @@ -214,8 +214,8 @@ public virtual void Dictionary_string_object_with_explicit_column_type_and_value modelBuilder.Entity() .Property(e => e.JsonProperty) .HasConversion( - v => JsonSerializer.Serialize(v, (JsonSerializerOptions)null), - v => JsonSerializer.Deserialize>(v, (JsonSerializerOptions)null)); + v => JsonSerializer.Serialize(v, (JsonSerializerOptions?)null), + v => JsonSerializer.Deserialize>(v, (JsonSerializerOptions?)null)!); Validate(modelBuilder); @@ -352,7 +352,7 @@ public virtual void Passes_on_json_path_index_in_single_complex_collection() var model = Validate(modelBuilder); var index = model.FindEntityType(typeof(EntityWithComplexCollection))!.GetIndexes().Single(); Assert.Equal("Value", index.Properties.Single().Name); - Assert.Equal(new int?[] { null }, index.CollectionIndices.Single()); + Assert.Equal(new int?[] { null }, index.CollectionIndices!.Single()); } [Fact] @@ -980,7 +980,7 @@ public virtual void Passes_on_shared_columns_with_shared_table() modelBuilder.Entity().ToTable("Table"); modelBuilder.Entity().Property(b => b.P0).HasColumnName(nameof(A.P0)).HasColumnType("someInt"); modelBuilder.Entity().Property(b => b.P3).HasColumnName(nameof(A.P3)) - .HasConversion(e => (long)e, e => (int?)e); + .HasConversion(e => (long)e!.Value, e => (int?)e); modelBuilder.Entity().ToTable("Table"); Validate(modelBuilder); @@ -1154,8 +1154,8 @@ public virtual void Passes_for_incompatible_uniquified_check_constraints_with_sh var model = Validate(modelBuilder); - Assert.Equal("CK_Table_SomeCK1", model.FindEntityType(typeof(A)).GetCheckConstraints().Single().Name); - Assert.Equal("CK_Table_SomeCK", model.FindEntityType(typeof(B)).GetCheckConstraints().Single().Name); + Assert.Equal("CK_Table_SomeCK1", model.FindEntityType(typeof(A))!.GetCheckConstraints().Single().Name); + Assert.Equal("CK_Table_SomeCK", model.FindEntityType(typeof(B))!.GetCheckConstraints().Single().Name); } [Fact] @@ -1169,8 +1169,8 @@ public virtual void Passes_for_compatible_shared_check_constraints_with_shared_t var model = Validate(modelBuilder); - Assert.Equal("CK_Table_SomeCK", model.FindEntityType(typeof(A)).GetCheckConstraints().Single().Name); - Assert.Equal("CK_Table_SomeCK", model.FindEntityType(typeof(B)).GetCheckConstraints().Single().Name); + Assert.Equal("CK_Table_SomeCK", model.FindEntityType(typeof(A))!.GetCheckConstraints().Single().Name); + Assert.Equal("CK_Table_SomeCK", model.FindEntityType(typeof(B))!.GetCheckConstraints().Single().Name); } [Fact] @@ -1181,7 +1181,7 @@ public virtual void Detects_multiple_shared_table_roots() modelBuilder.Entity().HasOne().WithOne().HasForeignKey(a => a.Id).HasPrincipalKey(b => b.Id).IsRequired(); modelBuilder.Entity().ToTable("Table"); modelBuilder.Entity().HasOne().WithOne().HasForeignKey(a => a.Id).HasPrincipalKey(b => b.Id).IsRequired(); - modelBuilder.Entity().HasBaseType((string)null).ToTable("Table"); + modelBuilder.Entity().HasBaseType((string?)null).ToTable("Table"); modelBuilder.Entity().ToTable("Table"); VerifyError( @@ -1247,7 +1247,7 @@ public virtual void Passes_for_compatible_excluded_shared_table_owned() var model = Validate(modelBuilder); - var b = model.FindEntityType(typeof(B)); + var b = model.FindEntityType(typeof(B))!; Assert.Equal("Table", b.GetTableName()); Assert.True(b.IsTableExcludedFromMigrations()); } @@ -1262,7 +1262,7 @@ public virtual void Passes_for_compatible_excluded_table_derived() var model = Validate(modelBuilder); - var c = model.FindEntityType(typeof(C)); + var c = model.FindEntityType(typeof(C))!; Assert.Equal("Table", c.GetTableName()); Assert.True(c.IsTableExcludedFromMigrations()); } @@ -1696,7 +1696,7 @@ public virtual void Passes_on_duplicate_column_names_with_different_column_nulla var model = Validate(modelBuilder); - var column = model.FindEntityType(typeof(B)).GetProperty(nameof(A.P0)).GetTableColumnMappings().Single().Column; + var column = model.FindEntityType(typeof(B))!.GetProperty(nameof(A.P0)).GetTableColumnMappings().Single().Column; Assert.Equal(2, column.PropertyMappings.Count()); Assert.False(column.IsNullable); @@ -1712,7 +1712,7 @@ public virtual void Passes_on_duplicate_column_names_within_hierarchy_with_same_ var model = Validate(modelBuilder); - var column = model.FindEntityType(typeof(Cat)).FindProperty("OtherId").GetTableColumnMappings().Single().Column; + var column = model.FindEntityType(typeof(Cat))!.FindProperty("OtherId")!.GetTableColumnMappings().Single().Column; Assert.Equal(2, column.PropertyMappings.Count()); Assert.True(column.IsNullable); @@ -2072,8 +2072,8 @@ public virtual void Passes_for_incompatible_foreignKeys_within_hierarchy_when_on public virtual void Passes_for_compatible_duplicate_foreignKey_names_within_hierarchy() { var modelBuilder = CreateConventionModelBuilder(); - IReadOnlyForeignKey fk1 = null; - IReadOnlyForeignKey fk2 = null; + IReadOnlyForeignKey fk1 = null!; + IReadOnlyForeignKey fk2 = null!; modelBuilder.Entity(); modelBuilder.Entity(et => @@ -2112,8 +2112,8 @@ public virtual void Passes_for_compatible_duplicate_foreignKey_names_within_hier public virtual void Passes_for_compatible_duplicate_foreignKey_names_within_hierarchy_name_configured_explicitly() { var modelBuilder = CreateConventionModelBuilder(); - IReadOnlyForeignKey fk1 = null; - IReadOnlyForeignKey fk2 = null; + IReadOnlyForeignKey fk1 = null!; + IReadOnlyForeignKey fk2 = null!; modelBuilder.Entity(); modelBuilder.Entity(et => @@ -2283,8 +2283,8 @@ public virtual void Passes_for_incompatible_indexes_within_hierarchy_when_one_na public virtual void Passes_for_compatible_duplicate_index_names_within_hierarchy() { var modelBuilder = CreateConventionModelBuilder(); - IMutableIndex index1 = null; - IMutableIndex index2 = null; + IMutableIndex index1 = null!; + IMutableIndex index2 = null!; modelBuilder.Entity(); modelBuilder.Entity(et => { @@ -2318,7 +2318,7 @@ private abstract class PropertyBase { public int Id { get; set; } - public Organization Organization { get; set; } + public Organization Organization { get; set; } = null!; } private class Organization @@ -2335,7 +2335,7 @@ private class Property : PropertyBase [Owned] private class PropertyDetails { - public Address Address { get; set; } + public Address Address { get; set; } = null!; } private class Address @@ -2401,7 +2401,7 @@ public virtual void Passes_for_missing_concurrency_token_property_on_the_base_ty var model = Validate(modelBuilder); - var animalType = model.FindEntityType(typeof(Animal)); + var animalType = model.FindEntityType(typeof(Animal))!; Assert.DoesNotContain(animalType.GetProperties(), p => p.IsConcurrencyToken); } @@ -2708,7 +2708,7 @@ public virtual void Passes_for_abstract_class_TPC() public virtual void Passes_for_view_TPC() { var modelBuilder = CreateConventionModelBuilder(); - modelBuilder.Entity().ToTable((string)null).UseTpcMappingStrategy(); + modelBuilder.Entity().ToTable((string?)null).UseTpcMappingStrategy(); modelBuilder.Entity().ToView("Cat"); Validate(modelBuilder); @@ -2730,7 +2730,7 @@ public virtual void Detects_invalid_MappingStrategy() public virtual void Detects_MappingStrategy_on_derived_types() { var modelBuilder = CreateConventionModelBuilder(); - modelBuilder.Entity().HasBaseType((string)null); + modelBuilder.Entity().HasBaseType((string?)null); modelBuilder.Entity(); modelBuilder.Entity().ToTable("Cat").ToView("Cat").UseTpcMappingStrategy().HasBaseType(typeof(Animal)); @@ -2936,7 +2936,7 @@ public virtual void Detects_owned_view_sharing_on_abstract_class_with_TPT() modelBuilder.Entity() .UseTptMappingStrategy() .OwnsOne( - b => b.Details, ob => ob.ToTable((string)null)); + b => b.Details, ob => ob.ToTable((string?)null)); modelBuilder.Entity() .ToView("Animal"); @@ -3139,7 +3139,7 @@ public void Detects_function_with_unmapped_return_type() var methodInfo = typeof(TestMethods) - .GetRuntimeMethod(nameof(TestMethods.MethodA), []); + .GetRuntimeMethod(nameof(TestMethods.MethodA), [])!; modelBuilder.HasDbFunction(methodInfo); @@ -3173,7 +3173,7 @@ public void Passes_for_valid_entity_type_mapped_to_function() var methodInfo = typeof(TestMethods) - .GetRuntimeMethod(nameof(TestMethods.MethodA), []); + .GetRuntimeMethod(nameof(TestMethods.MethodA), [])!; var function = modelBuilder.HasDbFunction(methodInfo).Metadata; @@ -3259,7 +3259,7 @@ public void Detects_multiple_entity_types_mapped_to_the_same_function() modelBuilder.Entity(db => { - db.HasBaseType((string)null); + db.HasBaseType((string?)null); db.OwnsOne(d => d.SomeTestMethods).ToFunction(function.ModelName); db.OwnsOne(d => d.OtherTestMethods).ToFunction(function.ModelName); }); @@ -3316,7 +3316,7 @@ public virtual void Detects_multiple_entity_types_mapped_to_the_same_stored_proc modelBuilder.Entity(db => { - db.HasBaseType((string)null); + db.HasBaseType((string?)null); db.OwnsOne(d => d.SomeTestMethods).DeleteUsingStoredProcedure( "Delete", s => s.HasOriginalValueParameter("DerivedTestMethodsId")); @@ -3355,7 +3355,7 @@ public virtual void Detects_tableless_entity_type_mapped_to_some_stored_procedur var modelBuilder = CreateConventionModelBuilder(); modelBuilder.Entity() .Ignore(a => a.FavoritePerson) - .ToTable((string)null) + .ToTable((string?)null) .InsertUsingStoredProcedure(s => s.HasParameter(c => c.Id).HasParameter(c => c.Name)) .UpdateUsingStoredProcedure(s => s.HasOriginalValueParameter(c => c.Id).HasParameter(c => c.Name)) .Property(a => a.Id).ValueGeneratedNever(); @@ -3941,7 +3941,7 @@ public void Passes_for_unnamed_index_with_all_properties_not_mapped_to_any_table { var modelBuilder = CreateConventionModelBuilder(); - modelBuilder.Entity().ToTable((string)null); + modelBuilder.Entity().ToTable((string?)null); modelBuilder.Entity().HasIndex(nameof(Animal.Id), nameof(Animal.Name)); var definition = RelationalResources @@ -3959,7 +3959,7 @@ public void Passes_for_named_index_with_all_properties_not_mapped_to_any_table() { var modelBuilder = CreateConventionModelBuilder(); - modelBuilder.Entity().ToTable((string)null); + modelBuilder.Entity().ToTable((string?)null); modelBuilder.Entity() .HasIndex( [nameof(Animal.Id), nameof(Animal.Name)], @@ -3981,7 +3981,7 @@ public void Passes_for_mix_of_index_properties_declared_and_inherited_TPT() { var modelBuilder = CreateConventionModelBuilder(); - modelBuilder.Entity().ToTable((string)null); + modelBuilder.Entity().ToTable((string?)null); modelBuilder.Entity().ToTable("Cats") .HasIndex( [nameof(Cat.Identity), nameof(Animal.Name)], @@ -3996,7 +3996,7 @@ public void Detects_mix_of_index_property_mapped_and_not_mapped_to_any_table_map var modelBuilder = CreateConventionModelBuilder(); modelBuilder.Entity(); - modelBuilder.Entity().ToTable((string)null) + modelBuilder.Entity().ToTable((string?)null) .HasIndex(nameof(Animal.Name), nameof(Cat.Identity)); var definition = RelationalResources @@ -4017,7 +4017,7 @@ public void Detects_mix_of_index_property_mapped_and_not_mapped_to_any_table_unm var modelBuilder = CreateConventionModelBuilder(); modelBuilder.Entity(); - modelBuilder.Entity().ToTable((string)null) + modelBuilder.Entity().ToTable((string?)null) .HasIndex( [nameof(Cat.Identity), nameof(Animal.Name)], "IX_MixOfMappedAndUnmappedProperties"); @@ -4117,7 +4117,7 @@ public virtual void Non_TPH_as_a_result_of_DbFunction_throws() VerifyError( RelationalStrings.TableValuedFunctionNonTph( - TestMethods.MethodFMi.DeclaringType.FullName + "." + TestMethods.MethodFMi.Name + "()", "C"), modelBuilder); + TestMethods.MethodFMi.DeclaringType!.FullName + "." + TestMethods.MethodFMi.Name + "()", "C"), modelBuilder); } [Fact] @@ -4221,7 +4221,7 @@ private class Outer { public class TpcDerived : TpcBase { - public string Value { get; set; } + public string Value { get; set; } = null!; } } @@ -4229,7 +4229,7 @@ private class Outer2 { public class TpcDerived : TpcBase { - public string Value { get; set; } + public string Value { get; set; } = null!; } } @@ -4257,7 +4257,7 @@ public class TestDecimalToDecimalConverter() private class BaseTestMethods { - public static readonly MethodInfo MethodAMi = typeof(BaseTestMethods).GetTypeInfo().GetDeclaredMethod(nameof(MethodA)); + public static readonly MethodInfo MethodAMi = typeof(BaseTestMethods).GetTypeInfo().GetDeclaredMethod(nameof(MethodA))!; public static IQueryable MethodA() => throw new NotImplementedException(); @@ -4266,18 +4266,18 @@ public static IQueryable MethodA() private class DerivedTestMethods : TestMethods { public int Id { get; set; } - public TestMethods SomeTestMethods { get; set; } - public TestMethods OtherTestMethods { get; set; } + public TestMethods SomeTestMethods { get; set; } = null!; + public TestMethods OtherTestMethods { get; set; } = null!; } private class TestMethods : BaseTestMethods { - public static new readonly MethodInfo MethodAMi = typeof(TestMethods).GetTypeInfo().GetDeclaredMethod(nameof(MethodA)); - public static readonly MethodInfo MethodBMi = typeof(TestMethods).GetTypeInfo().GetDeclaredMethod(nameof(MethodB)); - public static readonly MethodInfo MethodCMi = typeof(TestMethods).GetTypeInfo().GetDeclaredMethod(nameof(MethodC)); - public static readonly MethodInfo MethodDMi = typeof(TestMethods).GetTypeInfo().GetDeclaredMethod(nameof(MethodD)); - public static readonly MethodInfo MethodEMi = typeof(TestMethods).GetTypeInfo().GetDeclaredMethod(nameof(MethodE)); - public static readonly MethodInfo MethodFMi = typeof(TestMethods).GetTypeInfo().GetDeclaredMethod(nameof(MethodF)); + public static new readonly MethodInfo MethodAMi = typeof(TestMethods).GetTypeInfo().GetDeclaredMethod(nameof(MethodA))!; + public static readonly MethodInfo MethodBMi = typeof(TestMethods).GetTypeInfo().GetDeclaredMethod(nameof(MethodB))!; + public static readonly MethodInfo MethodCMi = typeof(TestMethods).GetTypeInfo().GetDeclaredMethod(nameof(MethodC))!; + public static readonly MethodInfo MethodDMi = typeof(TestMethods).GetTypeInfo().GetDeclaredMethod(nameof(MethodD))!; + public static readonly MethodInfo MethodEMi = typeof(TestMethods).GetTypeInfo().GetDeclaredMethod(nameof(MethodE))!; + public static readonly MethodInfo MethodFMi = typeof(TestMethods).GetTypeInfo().GetDeclaredMethod(nameof(MethodF))!; public static new IQueryable MethodA() => throw new NotImplementedException(); diff --git a/test/EFCore.Relational.Tests/Metadata/Conventions/Internal/TableValuedDbFunctionConventionTest.cs b/test/EFCore.Relational.Tests/Metadata/Conventions/Internal/TableValuedDbFunctionConventionTest.cs index 6fa2a8cb8d1..5b4af6d820c 100644 --- a/test/EFCore.Relational.Tests/Metadata/Conventions/Internal/TableValuedDbFunctionConventionTest.cs +++ b/test/EFCore.Relational.Tests/Metadata/Conventions/Internal/TableValuedDbFunctionConventionTest.cs @@ -14,12 +14,12 @@ public void Does_not_configure_return_entity_as_not_mapped() modelBuilder.HasDbFunction( typeof(TableValuedDbFunctionConventionTest).GetMethod( nameof(GetKeylessEntities), - BindingFlags.NonPublic | BindingFlags.Static)); + BindingFlags.NonPublic | BindingFlags.Static)!); modelBuilder.Entity().HasNoKey(); var model = Finalize(modelBuilder); - var entityType = model.FindEntityType(typeof(KeylessEntity)); + var entityType = model.FindEntityType(typeof(KeylessEntity))!; Assert.Null(entityType.FindPrimaryKey()); Assert.Equal("KeylessEntity", entityType.GetTableMappings().Single().Table.Name); @@ -33,13 +33,13 @@ public void Finds_existing_entity_type() modelBuilder.HasDbFunction( typeof(TableValuedDbFunctionConventionTest).GetMethod( nameof(GetEntities), - BindingFlags.NonPublic | BindingFlags.Static)); + BindingFlags.NonPublic | BindingFlags.Static)!); var model = Finalize(modelBuilder); - var entityType = model.FindEntityType(typeof(TestEntity)); + var entityType = model.FindEntityType(typeof(TestEntity))!; - Assert.Equal(nameof(TestEntity.Name), entityType.FindPrimaryKey().Properties.Single().Name); + Assert.Equal(nameof(TestEntity.Name), entityType.FindPrimaryKey()!.Properties.Single().Name); Assert.Equal("TestTable", entityType.GetTableMappings().Single().Table.Name); } @@ -51,7 +51,7 @@ public void Throws_when_adding_a_function_returning_an_owned_type() modelBuilder.HasDbFunction( typeof(TableValuedDbFunctionConventionTest).GetMethod( nameof(GetKeylessEntities), - BindingFlags.NonPublic | BindingFlags.Static)); + BindingFlags.NonPublic | BindingFlags.Static)!); Assert.Equal( RelationalStrings.DbFunctionInvalidIQueryableOwnedReturnType( @@ -68,7 +68,7 @@ public void Throws_when_adding_a_function_returning_an_existing_owned_type() modelBuilder.HasDbFunction( typeof(TableValuedDbFunctionConventionTest).GetMethod( nameof(GetKeylessEntities), - BindingFlags.NonPublic | BindingFlags.Static)); + BindingFlags.NonPublic | BindingFlags.Static)!); Assert.Equal( RelationalStrings.DbFunctionInvalidIQueryableOwnedReturnType( @@ -84,7 +84,7 @@ public void Throws_when_adding_a_function_returning_a_scalar() modelBuilder.HasDbFunction( typeof(TableValuedDbFunctionConventionTest).GetMethod( nameof(GetScalars), - BindingFlags.NonPublic | BindingFlags.Static)); + BindingFlags.NonPublic | BindingFlags.Static)!); Assert.Equal( RelationalStrings.DbFunctionInvalidIQueryableReturnType( @@ -112,14 +112,14 @@ private class TestEntity { public int Id { get; set; } - public string Name { get; set; } + public string Name { get; set; } = null!; [NotMapped] - public KeylessEntity KeylessEntity { get; set; } + public KeylessEntity KeylessEntity { get; set; } = null!; } private class KeylessEntity { - public string Name { get; set; } + public string Name { get; set; } = null!; } } diff --git a/test/EFCore.Relational.Tests/Metadata/Conventions/TableSharingConcurrencyTokenConventionTest.cs b/test/EFCore.Relational.Tests/Metadata/Conventions/TableSharingConcurrencyTokenConventionTest.cs index e729ccb58e5..148f8eb0692 100644 --- a/test/EFCore.Relational.Tests/Metadata/Conventions/TableSharingConcurrencyTokenConventionTest.cs +++ b/test/EFCore.Relational.Tests/Metadata/Conventions/TableSharingConcurrencyTokenConventionTest.cs @@ -25,8 +25,8 @@ public virtual void Missing_concurrency_token_property_is_created_on_the_base_ty var model = modelBuilder.Model; model.FinalizeModel(); - var animal = model.FindEntityType(typeof(Animal)); - var concurrencyProperty = animal.FindProperty("_TableSharingConcurrencyTokenConvention_Version"); + var animal = model.FindEntityType(typeof(Animal))!; + var concurrencyProperty = animal.FindProperty("_TableSharingConcurrencyTokenConvention_Version")!; Assert.True(concurrencyProperty.IsConcurrencyToken); Assert.True(concurrencyProperty.IsShadowProperty()); Assert.Equal("Version", concurrencyProperty.GetColumnName()); @@ -49,7 +49,7 @@ public virtual void Missing_concurrency_token_property_is_not_created_for_TPT() var model = modelBuilder.Model; model.FinalizeModel(); - var person = model.FindEntityType(typeof(Person)); + var person = model.FindEntityType(typeof(Person))!; Assert.DoesNotContain(person.GetProperties(), p => p.IsConcurrencyToken); } @@ -69,7 +69,7 @@ public virtual void Missing_concurrency_token_property_is_created_for_TPT_same_t var model = modelBuilder.Model; model.FinalizeModel(); - var person = model.FindEntityType(typeof(Person)); + var person = model.FindEntityType(typeof(Person))!; Assert.Contains(person.GetProperties(), p => p.IsConcurrencyToken); } @@ -86,7 +86,7 @@ public virtual void Missing_concurrency_token_property_is_not_created_for_TPH() var model = modelBuilder.Model; model.FinalizeModel(); - var person = model.FindEntityType(typeof(Animal)); + var person = model.FindEntityType(typeof(Animal))!; Assert.DoesNotContain(person.GetProperties(), p => p.IsConcurrencyToken); } @@ -110,24 +110,24 @@ public virtual void Missing_concurrency_token_properties_are_created_on_the_base var model = modelBuilder.Model; model.FinalizeModel(); - var animal = model.FindEntityType(typeof(Animal)); - var concurrencyProperty = animal.FindProperty("_TableSharingConcurrencyTokenConvention_Version"); + var animal = model.FindEntityType(typeof(Animal))!; + var concurrencyProperty = animal.FindProperty("_TableSharingConcurrencyTokenConvention_Version")!; Assert.True(concurrencyProperty.IsConcurrencyToken); Assert.True(concurrencyProperty.IsShadowProperty()); Assert.Equal("Version", concurrencyProperty.GetColumnName()); Assert.Equal(ValueGenerated.OnUpdate, concurrencyProperty.ValueGenerated); - var cat = model.FindEntityType(typeof(Cat)); + var cat = model.FindEntityType(typeof(Cat))!; Assert.DoesNotContain(cat.GetDeclaredProperties(), p => p.Name == "_TableSharingConcurrencyTokenConvention_Version"); - var animalHouse = model.FindEntityType(typeof(AnimalHouse)); - concurrencyProperty = animalHouse.FindProperty("_TableSharingConcurrencyTokenConvention_Version"); + var animalHouse = model.FindEntityType(typeof(AnimalHouse))!; + concurrencyProperty = animalHouse.FindProperty("_TableSharingConcurrencyTokenConvention_Version")!; Assert.True(concurrencyProperty.IsConcurrencyToken); Assert.True(concurrencyProperty.IsShadowProperty()); Assert.Equal("Version", concurrencyProperty.GetColumnName()); Assert.Equal(ValueGenerated.OnUpdate, concurrencyProperty.ValueGenerated); - var theMovie = model.FindEntityType(typeof(TheMovie)); + var theMovie = model.FindEntityType(typeof(TheMovie))!; Assert.DoesNotContain(theMovie.GetDeclaredProperties(), p => p.Name == "_TableSharingConcurrencyTokenConvention_Version"); } @@ -144,8 +144,8 @@ public virtual void Missing_concurrency_token_property_is_created_on_the_sharing var model = modelBuilder.Model; model.FinalizeModel(); - var personEntityType = model.FindEntityType(typeof(Person)); - var concurrencyProperty = personEntityType.FindProperty("_TableSharingConcurrencyTokenConvention_Version"); + var personEntityType = model.FindEntityType(typeof(Person))!; + var concurrencyProperty = personEntityType.FindProperty("_TableSharingConcurrencyTokenConvention_Version")!; Assert.True(concurrencyProperty.IsConcurrencyToken); Assert.True(concurrencyProperty.IsShadowProperty()); Assert.Equal("Version", concurrencyProperty.GetColumnName()); @@ -169,14 +169,14 @@ public virtual void Missing_concurrency_token_property_is_created_on_the_sharing var model = modelBuilder.Model; model.FinalizeModel(); - var personEntityType = model.FindEntityType(typeof(Person)); - var concurrencyProperty = personEntityType.FindProperty("_TableSharingConcurrencyTokenConvention_Version"); + var personEntityType = model.FindEntityType(typeof(Person))!; + var concurrencyProperty = personEntityType.FindProperty("_TableSharingConcurrencyTokenConvention_Version")!; Assert.True(concurrencyProperty.IsConcurrencyToken); Assert.True(concurrencyProperty.IsShadowProperty()); Assert.Equal("Version", concurrencyProperty.GetColumnName()); Assert.Equal(ValueGenerated.OnAddOrUpdate, concurrencyProperty.ValueGenerated); - var animalEntityType = model.FindEntityType(typeof(Animal)); + var animalEntityType = model.FindEntityType(typeof(Animal))!; Assert.All(animalEntityType.GetProperties(), p => Assert.NotEqual(typeof(byte[]), p.ClrType)); } @@ -198,7 +198,7 @@ public virtual void Concurrency_token_property_is_not_created_on_the_sharing_whe var model = modelBuilder.Model; model.FinalizeModel(); - var animalEntityType = model.FindEntityType(typeof(Animal)); + var animalEntityType = model.FindEntityType(typeof(Animal))!; Assert.All(animalEntityType.GetProperties(), p => Assert.NotEqual(typeof(byte[]), p.ClrType)); } @@ -252,18 +252,18 @@ protected class OwnedEntity protected class Animal { public int Id { get; set; } - public string Name { get; set; } + public string Name { get; set; } = null!; - public Person FavoritePerson { get; set; } - public AnimalHouse Dwelling { get; set; } + public Person FavoritePerson { get; set; } = null!; + public AnimalHouse Dwelling { get; set; } = null!; } protected class Cat : Animal { - public string Breed { get; set; } + public string Breed { get; set; } = null!; [NotMapped] - public string Type { get; set; } + public string Type { get; set; } = null!; public int Identity { get; set; } } @@ -281,11 +281,11 @@ protected class TheMovie : AnimalHouse protected class Person { public int Id { get; set; } - public string Name { get; set; } - public string FavoriteBreed { get; set; } + public string Name { get; set; } = null!; + public string FavoriteBreed { get; set; } = null!; } - private ModelBuilder GetModelBuilder(DbContext dbContext = null) + private ModelBuilder GetModelBuilder(DbContext? dbContext = null) { var conventionSet = new ConventionSet(); diff --git a/test/EFCore.Relational.Tests/Metadata/DbFunctionTest.cs b/test/EFCore.Relational.Tests/Metadata/DbFunctionTest.cs index 5cdf44a834b..1556ecf7334 100644 --- a/test/EFCore.Relational.Tests/Metadata/DbFunctionTest.cs +++ b/test/EFCore.Relational.Tests/Metadata/DbFunctionTest.cs @@ -204,17 +204,17 @@ public IQueryable QueryableMultiParam(Expression> i, Expression TestMethods.MethodA(null, default)); + var dbFuncBuilder = modelBuilder.HasDbFunction(() => TestMethods.MethodA(null!, default)); var dbFunc = dbFuncBuilder.Metadata; modelBuilder.FinalizeModel(); Assert.Equal("MethodA", dbFunc.Name); Assert.Null(dbFunc.Schema); - Assert.Equal(typeof(int), dbFunc.MethodInfo.ReturnType); + Assert.Equal(typeof(int), dbFunc.MethodInfo!.ReturnType); } [Fact] @@ -426,7 +426,7 @@ public void Adding_method_fluent_only_with_name_schema() Assert.Equal("foo", dbFunc.Name); Assert.Equal("bar", dbFunc.Schema); - Assert.Equal(typeof(int), dbFunc.MethodInfo.ReturnType); + Assert.Equal(typeof(int), dbFunc.MethodInfo!.ReturnType); } [Fact] @@ -442,7 +442,7 @@ public void Adding_method_fluent_only_with_builder() Assert.Equal("foo", dbFunc.Name); Assert.Equal("bar", dbFunc.Schema); - Assert.Equal(typeof(int), dbFunc.MethodInfo.ReturnType); + Assert.Equal(typeof(int), dbFunc.MethodInfo!.ReturnType); } [Fact] @@ -457,7 +457,7 @@ public void Adding_method_with_attribute_only() Assert.Equal("MethodFoo", dbFunc.Name); Assert.Equal("bar", dbFunc.Schema); - Assert.Equal(typeof(int), dbFunc.MethodInfo.ReturnType); + Assert.Equal(typeof(int), dbFunc.MethodInfo!.ReturnType); } [Fact] @@ -466,7 +466,7 @@ public void Adding_method_with_attribute_and_fluent_api_configuration_source() var modelBuilder = GetModelBuilder(); var dbFuncBuilder = modelBuilder.HasDbFunction(MethodBmi) - .HasName(null) + .HasName(null!) .HasSchema(null); var dbFunc = dbFuncBuilder.Metadata; @@ -481,7 +481,7 @@ public void Adding_method_with_attribute_and_fluent_api_configuration_source() Assert.Equal("foo", dbFunc.Name); Assert.Equal("BAR", dbFunc.Schema); - Assert.Equal(typeof(int), dbFunc.MethodInfo.ReturnType); + Assert.Equal(typeof(int), dbFunc.MethodInfo!.ReturnType); } [Fact] @@ -489,7 +489,7 @@ public void Adding_method_with_attribute_and_fluent_configuration_source() { var modelBuilder = GetModelBuilder(); - modelBuilder.HasDbFunction(MethodBmi, funcBuilder => funcBuilder.HasName(null).HasSchema(null)); + modelBuilder.HasDbFunction(MethodBmi, funcBuilder => funcBuilder.HasName(null!).HasSchema(null)); var dbFuncBuilder = modelBuilder.HasDbFunction(MethodBmi); var dbFunc = dbFuncBuilder.Metadata; @@ -504,7 +504,7 @@ public void Adding_method_with_attribute_and_fluent_configuration_source() Assert.Equal("foo", dbFunc.Name); Assert.Equal("BAR", dbFunc.Schema); - Assert.Equal(typeof(int), dbFunc.MethodInfo.ReturnType); + Assert.Equal(typeof(int), dbFunc.MethodInfo!.ReturnType); } [Fact] @@ -594,8 +594,8 @@ public void DbFunction_HasName() { var modelBuilder = GetModelBuilder(); - var methodA = typeof(OuterA.Inner).GetMethod(nameof(OuterA.Inner.Min)); - var methodB = typeof(OuterB.Inner).GetMethod(nameof(OuterB.Inner.Min)); + var methodA = typeof(OuterA.Inner).GetMethod(nameof(OuterA.Inner.Min))!; + var methodB = typeof(OuterB.Inner).GetMethod(nameof(OuterB.Inner.Min))!; var funcA = modelBuilder.HasDbFunction(methodA); var funcB = modelBuilder.HasDbFunction(methodB); @@ -614,7 +614,7 @@ public void DbFunction_IsBuiltIn() { var modelBuilder = GetModelBuilder(); - var methodA = typeof(OuterA.Inner).GetMethod(nameof(OuterA.Inner.Min)); + var methodA = typeof(OuterA.Inner).GetMethod(nameof(OuterA.Inner.Min))!; var funcA = modelBuilder.HasDbFunction(methodA); @@ -655,13 +655,13 @@ public void DbFunction_IsQueryable() var queryableNoParams = typeof(MyDerivedContext) - .GetRuntimeMethod(nameof(MyDerivedContext.QueryableNoParams), []); + .GetRuntimeMethod(nameof(MyDerivedContext.QueryableNoParams), [])!; var functionName = modelBuilder.HasDbFunction(queryableNoParams).Metadata.ModelName; var model = modelBuilder.FinalizeModel(skipValidation: true); - var function = model.FindDbFunction(functionName); + var function = model.FindDbFunction(functionName)!; var entityType = model.FindEntityType(typeof(Foo)); Assert.False(function.IsScalar); @@ -678,7 +678,7 @@ public void IsNullable_throws_for_nonScalar() var queryableNoParams = typeof(MyDerivedContext) - .GetRuntimeMethod(nameof(MyDerivedContext.QueryableNoParams), []); + .GetRuntimeMethod(nameof(MyDerivedContext.QueryableNoParams), [])!; Assert.Equal( RelationalStrings.NonScalarFunctionCannotBeNullable(nameof(MyDerivedContext.QueryableNoParams)), @@ -691,7 +691,7 @@ public void PropagatesNullability_throws_for_nonScalar() var modelBuilder = GetModelBuilder(); var queryableSingleParam = typeof(MyDerivedContext) - .GetRuntimeMethod(nameof(MyDerivedContext.QueryableSingleParam), [typeof(int)]); + .GetRuntimeMethod(nameof(MyDerivedContext.QueryableSingleParam), [typeof(int)])!; var function = modelBuilder.HasDbFunction(queryableSingleParam); var parameter = function.HasParameter("i"); @@ -709,7 +709,7 @@ public void DbParameters_invalid_parameter_name_throws() var dbFuncBuilder = modelBuilder.HasDbFunction(MethodBmi); Assert.Equal( - RelationalStrings.DbFunctionInvalidParameterName(dbFuncBuilder.Metadata.MethodInfo.DisplayName(), "q"), + RelationalStrings.DbFunctionInvalidParameterName(dbFuncBuilder.Metadata.MethodInfo!.DisplayName(), "q"), Assert.Throws(() => dbFuncBuilder.HasParameter("q")).Message); } @@ -800,7 +800,7 @@ public void DbParameters_StoreType() public void DbFunction_Queryable_custom_translation() { var modelBuilder = GetModelBuilder(); - var methodInfo = typeof(TestMethods).GetMethod(nameof(TestMethods.MethodJ)); + var methodInfo = typeof(TestMethods).GetMethod(nameof(TestMethods.MethodJ))!; var dbFunctionBuilder = modelBuilder.HasDbFunction(methodInfo); Assert.False( diff --git a/test/EFCore.Relational.Tests/Metadata/RelationalEntityTypeAttributeConventionTest.cs b/test/EFCore.Relational.Tests/Metadata/RelationalEntityTypeAttributeConventionTest.cs index 196339f1faf..2ffeb8a0c08 100644 --- a/test/EFCore.Relational.Tests/Metadata/RelationalEntityTypeAttributeConventionTest.cs +++ b/test/EFCore.Relational.Tests/Metadata/RelationalEntityTypeAttributeConventionTest.cs @@ -102,7 +102,7 @@ private InternalEntityTypeBuilder CreateInternalEntityTypeBuilder() var modelBuilder = new InternalModelBuilder(new Model(conventionSet)); - return modelBuilder.Entity(typeof(T), ConfigurationSource.Explicit); + return modelBuilder.Entity(typeof(T), ConfigurationSource.Explicit)!; } private ProviderConventionSetBuilderDependencies CreateDependencies() @@ -119,6 +119,6 @@ private class A { public int Id { get; set; } - public string Name { get; set; } + public string Name { get; set; } = null!; } } diff --git a/test/EFCore.Relational.Tests/Metadata/RelationalJsonIndexTest.cs b/test/EFCore.Relational.Tests/Metadata/RelationalJsonIndexTest.cs index 0ba302adc58..be1b9d141b1 100644 --- a/test/EFCore.Relational.Tests/Metadata/RelationalJsonIndexTest.cs +++ b/test/EFCore.Relational.Tests/Metadata/RelationalJsonIndexTest.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable - namespace Microsoft.EntityFrameworkCore.Metadata; public class RelationalJsonIndexTest diff --git a/test/EFCore.Relational.Tests/Metadata/RelationalModelTest.cs b/test/EFCore.Relational.Tests/Metadata/RelationalModelTest.cs index 282ddf545d9..6f497af875c 100644 --- a/test/EFCore.Relational.Tests/Metadata/RelationalModelTest.cs +++ b/test/EFCore.Relational.Tests/Metadata/RelationalModelTest.cs @@ -191,7 +191,7 @@ public void Can_use_relational_model_with_tables_and_views(Mapping mapping) private static void AssertDefaultMappings(IRelationalModel model, Mapping mapping) { - var orderType = model.Model.FindEntityType(typeof(Order)); + var orderType = model.Model.FindEntityType(typeof(Order))!; var orderMapping = orderType.GetDefaultMappings().Single(); Assert.Null(orderMapping.IncludesDerivedTypes); Assert.Equal( @@ -211,19 +211,19 @@ private static void AssertDefaultMappings(IRelationalModel model, Mapping mappin Assert.Equal("Microsoft.EntityFrameworkCore.Metadata.RelationalModelTest+Order", ordersTable.Name); Assert.Null(ordersTable.Schema); - var orderDate = orderType.FindProperty(nameof(Order.OrderDate)); + var orderDate = orderType.FindProperty(nameof(Order.OrderDate))!; var orderDateMapping = orderDate.GetDefaultColumnMappings().Single(); Assert.NotNull(orderDateMapping.TypeMapping); Assert.Equal("default_datetime_mapping", orderDateMapping.TypeMapping.StoreType); Assert.Same(orderMapping, orderDateMapping.TableMapping); - var abstractBaseType = model.Model.FindEntityType(typeof(AbstractBase)); - var abstractCustomerType = model.Model.FindEntityType(typeof(AbstractCustomer)); - var customerType = model.Model.FindEntityType(typeof(Customer)); - var specialCustomerType = model.Model.FindEntityType(typeof(SpecialCustomer)); - var extraSpecialCustomerType = model.Model.FindEntityType(typeof(ExtraSpecialCustomer)); - var orderDetailsOwnership = orderType.FindNavigation(nameof(Order.Details)).ForeignKey; + var abstractBaseType = model.Model.FindEntityType(typeof(AbstractBase))!; + var abstractCustomerType = model.Model.FindEntityType(typeof(AbstractCustomer))!; + var customerType = model.Model.FindEntityType(typeof(Customer))!; + var specialCustomerType = model.Model.FindEntityType(typeof(SpecialCustomer))!; + var extraSpecialCustomerType = model.Model.FindEntityType(typeof(ExtraSpecialCustomer))!; + var orderDetailsOwnership = orderType.FindNavigation(nameof(Order.Details))!.ForeignKey; var orderDetailsType = orderDetailsOwnership.DeclaringEntityType; var orderDetailsTable = orderDetailsType.GetDefaultMappings().Single().Table; Assert.Same(ordersTable, orderDetailsTable); @@ -232,12 +232,12 @@ private static void AssertDefaultMappings(IRelationalModel model, Mapping mappin RelationalStrings.TableNotMappedEntityType(nameof(SpecialCustomer), ordersTable.Name), Assert.Throws(() => ordersTable.IsOptional(specialCustomerType)).Message); - var orderDetailsDate = orderDetailsType.FindProperty(nameof(OrderDetails.OrderDate)); + var orderDetailsDate = orderDetailsType.FindProperty(nameof(OrderDetails.OrderDate))!; var orderDateColumn = orderDateMapping.Column; Assert.Same(orderDateColumn, ordersTable.FindColumn("OrderDate")); Assert.Same(orderDateColumn, ordersTable.FindColumn(orderDate)); Assert.Equal([orderDate, orderDetailsDate], orderDateColumn.PropertyMappings.Select(m => m.Property)); - Assert.Equal([orderDate, orderDetailsDate], orderDetailsTable.FindColumn("OrderDate").PropertyMappings.Select(m => m.Property)); + Assert.Equal([orderDate, orderDetailsDate], orderDetailsTable.FindColumn("OrderDate")!.PropertyMappings.Select(m => m.Property)); Assert.Equal("OrderDate", orderDateColumn.Name); Assert.Equal("default_datetime_mapping", orderDateColumn.StoreType); Assert.False(orderDateColumn.IsNullable); @@ -357,20 +357,20 @@ private static void AssertViews(IRelationalModel model, Mapping mapping) Assert.Equal("viewSchema", ordersView.Schema); Assert.Null(ordersView.ViewDefinitionSql); - var orderPk = orderType.FindPrimaryKey(); + var orderPk = orderType.FindPrimaryKey()!; - var orderDate = orderType.FindProperty(nameof(Order.OrderDate)); + var orderDate = orderType.FindProperty(nameof(Order.OrderDate))!; var orderDateMapping = orderDate.GetViewColumnMappings().Single(); Assert.NotNull(orderDateMapping.TypeMapping); Assert.Equal("default_datetime_mapping", orderDateMapping.TypeMapping.StoreType); Assert.Same(orderMapping, orderDateMapping.ViewMapping); - var abstractBaseType = model.Model.FindEntityType(typeof(AbstractBase)); - var abstractCustomerType = model.Model.FindEntityType(typeof(AbstractCustomer)); + var abstractBaseType = model.Model.FindEntityType(typeof(AbstractBase))!; + var abstractCustomerType = model.Model.FindEntityType(typeof(AbstractCustomer))!; var customerType = model.Model.FindEntityType(typeof(Customer))!; var specialCustomerType = model.Model.FindEntityType(typeof(SpecialCustomer))!; var extraSpecialCustomerType = model.Model.FindEntityType(typeof(ExtraSpecialCustomer))!; - var orderDetailsOwnership = orderType.FindNavigation(nameof(Order.Details)).ForeignKey; + var orderDetailsOwnership = orderType.FindNavigation(nameof(Order.Details))!.ForeignKey; var orderDetailsType = orderDetailsOwnership.DeclaringEntityType; Assert.Same(ordersView, orderDetailsType.GetViewMappings().Single().View); Assert.Equal( @@ -393,7 +393,7 @@ private static void AssertViews(IRelationalModel model, Mapping mapping) Assert.Same(orderDateColumn, orderDate.FindColumn(StoreObjectIdentifier.View(ordersView.Name, ordersView.Schema))); Assert.Same(orderDateColumn, ordersView.FindColumn(orderDate)); - var orderDetailsDate = orderDetailsType.FindProperty(nameof(OrderDetails.OrderDate)); + var orderDetailsDate = orderDetailsType.FindProperty(nameof(OrderDetails.OrderDate))!; Assert.Equal([orderDate, orderDetailsDate], orderDateColumn.PropertyMappings.Select(m => m.Property)); Assert.Equal("OrderDate", orderDateColumn.Name); Assert.Equal("default_datetime_mapping", orderDateColumn.StoreType); @@ -418,7 +418,7 @@ private static void AssertViews(IRelationalModel model, Mapping mapping) ? abstractBaseType.GetTableName() : customerType.GetTableName(); var mappedToTable = baseTableName != null; - var ordersCustomerForeignKey = orderType.FindNavigation(nameof(Order.Customer)).ForeignKey; + var ordersCustomerForeignKey = orderType.FindNavigation(nameof(Order.Customer))!.ForeignKey; Assert.Equal( mappedToTable && mapping != Mapping.TPC ? "FK_Order_" + baseTableName + "_CustomerId" @@ -436,7 +436,7 @@ private static void AssertViews(IRelationalModel model, Mapping mapping) StoreObjectIdentifier.View(ordersView.Name, ordersView.Schema), StoreObjectIdentifier.View(customerView.Name, customerView.Schema))); - var ordersCustomerIndex = orderType.FindIndex(ordersCustomerForeignKey.Properties); + var ordersCustomerIndex = orderType.FindIndex(ordersCustomerForeignKey.Properties)!; Assert.Equal( mappedToTable ? "IX_Order_CustomerId" @@ -567,7 +567,7 @@ private static void AssertViews(IRelationalModel model, Mapping mapping) private static void AssertTables(IRelationalModel model, Mapping mapping) { - var orderType = model.Model.FindEntityType(typeof(Order)); + var orderType = model.Model.FindEntityType(typeof(Order))!; var orderMapping = orderType.GetTableMappings().Single(); Assert.Null(orderMapping.IncludesDerivedTypes); Assert.Equal( @@ -601,7 +601,7 @@ private static void AssertTables(IRelationalModel model, Mapping mapping) Assert.False(ordersTable.IsExcludedFromMigrations); Assert.True(ordersTable.IsShared); - var orderDate = orderType.FindProperty(nameof(Order.OrderDate)); + var orderDate = orderType.FindProperty(nameof(Order.OrderDate))!; var orderDateMapping = orderDate.GetTableColumnMappings().Single(); Assert.NotNull(orderDateMapping.TypeMapping); @@ -618,7 +618,7 @@ private static void AssertTables(IRelationalModel model, Mapping mapping) Assert.Same(ordersTable, orderDateColumn.Table); Assert.Same(orderDateMapping, orderDateColumn.FindColumnMapping(orderType)); - var orderPk = orderType.FindPrimaryKey(); + var orderPk = orderType.FindPrimaryKey()!; var orderPkConstraint = orderPk.GetMappedConstraints().Single(); Assert.Equal("PK_Order", orderPkConstraint.Name); @@ -669,12 +669,12 @@ private static void AssertTables(IRelationalModel model, Mapping mapping) var orderCustomerFk = orderType.GetForeignKeys().Single(fk => fk.PrincipalEntityType.ClrType == typeof(Customer)); - var abstractBaseType = model.Model.FindEntityType(typeof(AbstractBase)); - var abstractCustomerType = model.Model.FindEntityType(typeof(AbstractCustomer)); - var customerType = model.Model.FindEntityType(typeof(Customer)); - var specialCustomerType = model.Model.FindEntityType(typeof(SpecialCustomer)); - var extraSpecialCustomerType = model.Model.FindEntityType(typeof(ExtraSpecialCustomer)); - var orderDetailsOwnership = orderType.FindNavigation(nameof(Order.Details)).ForeignKey; + var abstractBaseType = model.Model.FindEntityType(typeof(AbstractBase))!; + var abstractCustomerType = model.Model.FindEntityType(typeof(AbstractCustomer))!; + var customerType = model.Model.FindEntityType(typeof(Customer))!; + var specialCustomerType = model.Model.FindEntityType(typeof(SpecialCustomer))!; + var extraSpecialCustomerType = model.Model.FindEntityType(typeof(ExtraSpecialCustomer))!; + var orderDetailsOwnership = orderType.FindNavigation(nameof(Order.Details))!.ForeignKey; var orderDetailsType = orderDetailsOwnership.DeclaringEntityType; Assert.Same(ordersTable, orderDetailsType.GetTableMappings().Single().Table); Assert.Equal( @@ -699,18 +699,18 @@ private static void AssertTables(IRelationalModel model, Mapping mapping) Assert.Same(orderDateTableIndex, orderDetailsDateTableIndex); Assert.Equal([orderDateIndex, orderDetailsDateIndex], orderDateTableIndex.MappedIndexes); - var orderDetailsPk = orderDetailsType.FindPrimaryKey(); + var orderDetailsPk = orderDetailsType.FindPrimaryKey()!; Assert.Same(orderPkConstraint, orderDetailsPk.GetMappedConstraints().Single()); var orderDetailsPkProperty = orderDetailsPk.Properties.Single(); Assert.Equal("OrderId", orderDetailsPkProperty.GetColumnName()); - var billingAddressOwnership = orderDetailsType.FindNavigation(nameof(OrderDetails.BillingAddress)).ForeignKey; + var billingAddressOwnership = orderDetailsType.FindNavigation(nameof(OrderDetails.BillingAddress))!.ForeignKey; Assert.True(billingAddressOwnership.IsRequiredDependent); var billingAddressType = billingAddressOwnership.DeclaringEntityType; - var shippingAddressOwnership = orderDetailsType.FindNavigation(nameof(OrderDetails.ShippingAddress)).ForeignKey; + var shippingAddressOwnership = orderDetailsType.FindNavigation(nameof(OrderDetails.ShippingAddress))!.ForeignKey; Assert.True(shippingAddressOwnership.IsRequiredDependent); var shippingAddressType = shippingAddressOwnership.DeclaringEntityType; @@ -734,7 +734,7 @@ private static void AssertTables(IRelationalModel model, Mapping mapping) Assert.Equal("FK_DateDetails", orderDateFkConstraint.Name); - var ordersCustomerIndex = orderType.FindIndex(orderCustomerFk.Properties); + var ordersCustomerIndex = orderType.FindIndex(orderCustomerFk.Properties)!; Assert.Equal("IX_Order_CustomerId", ordersCustomerIndex.GetDatabaseName()); Assert.Equal( "IX_Order_CustomerId", ordersCustomerIndex.GetDatabaseName( @@ -784,7 +784,7 @@ private static void AssertTables(IRelationalModel model, Mapping mapping) Assert.Equal("Order", orderTrigger.GetTableName()); Assert.Null(orderTrigger.GetTableSchema()); - var customerPk = specialCustomerType.FindPrimaryKey(); + var customerPk = specialCustomerType.FindPrimaryKey()!; var complexType = abstractBaseType.GetComplexProperties().Single().ComplexType; @@ -843,7 +843,7 @@ private static void AssertTables(IRelationalModel model, Mapping mapping) Assert.Empty(extraSpecialCustomerTable.CheckConstraints); Assert.Equal(4, customerPk.GetMappedConstraints().Count()); - var specialCustomerPkConstraint = specialCustomerTable.PrimaryKey; + var specialCustomerPkConstraint = specialCustomerTable.PrimaryKey!; Assert.Equal("PK_SpecialCustomer", specialCustomerPkConstraint.Name); Assert.Same(specialCustomerPkConstraint.MappedKeys.First(), customerPk); @@ -934,7 +934,7 @@ private static void AssertTables(IRelationalModel model, Mapping mapping) var specialtyColumn = specialCustomerTable.Columns.Single(c => c.Name == nameof(SpecialCustomer.Specialty)); - var specialCustomerPkConstraint = specialCustomerTable.PrimaryKey; + var specialCustomerPkConstraint = specialCustomerTable.PrimaryKey!; var specialCustomerUniqueConstraint = specialCustomerTable.UniqueConstraints.Single(c => !c.GetIsPrimaryKey()); var specialCustomerDbIndex = specialCustomerTable.Indexes.Last(); var anotherSpecialCustomerDbIndex = specialCustomerTable.Indexes.First(); @@ -1109,7 +1109,7 @@ private static void AssertTables(IRelationalModel model, Mapping mapping) private static void AssertSprocs(IRelationalModel model, Mapping mapping, bool mappedToTables = false) { - var orderType = model.Model.FindEntityType(typeof(Order)); + var orderType = model.Model.FindEntityType(typeof(Order))!; var orderInsertMapping = orderType.GetInsertStoredProcedureMappings().Single(); Assert.Null(orderInsertMapping.IncludesDerivedTypes); Assert.Same(orderType.GetInsertStoredProcedure(), orderInsertMapping.StoredProcedure); @@ -1146,7 +1146,7 @@ private static void AssertSprocs(IRelationalModel model, Mapping mapping, bool m ordersInsertSproc.ResultColumns.Select(m => m.Name)); Assert.Equal(ordersInsertSproc.ResultColumns, ordersInsertSproc.Columns); - var orderDate = orderType.FindProperty(nameof(Order.OrderDate)); + var orderDate = orderType.FindProperty(nameof(Order.OrderDate))!; var orderDateInsertMapping = orderDate.GetInsertStoredProcedureParameterMappings().Single(); Assert.NotNull(orderDateInsertMapping.TypeMapping); @@ -1165,12 +1165,12 @@ private static void AssertSprocs(IRelationalModel model, Mapping mapping, bool m Assert.Same(orderDateParameter.StoredProcedure, orderDateParameter.Table); Assert.Same(orderDateInsertMapping, orderDateParameter.FindParameterMapping(orderType)); - var abstractBaseType = model.Model.FindEntityType(typeof(AbstractBase)); - var abstractCustomerType = model.Model.FindEntityType(typeof(AbstractCustomer)); - var customerType = model.Model.FindEntityType(typeof(Customer)); - var specialCustomerType = model.Model.FindEntityType(typeof(SpecialCustomer)); - var extraSpecialCustomerType = model.Model.FindEntityType(typeof(ExtraSpecialCustomer)); - var orderDetailsOwnership = orderType.FindNavigation(nameof(Order.Details)).ForeignKey; + var abstractBaseType = model.Model.FindEntityType(typeof(AbstractBase))!; + var abstractCustomerType = model.Model.FindEntityType(typeof(AbstractCustomer))!; + var customerType = model.Model.FindEntityType(typeof(Customer))!; + var specialCustomerType = model.Model.FindEntityType(typeof(SpecialCustomer))!; + var extraSpecialCustomerType = model.Model.FindEntityType(typeof(ExtraSpecialCustomer))!; + var orderDetailsOwnership = orderType.FindNavigation(nameof(Order.Details))!.ForeignKey; var orderDetailsType = orderDetailsOwnership.DeclaringEntityType; Assert.Empty(ordersInsertSproc.GetReferencingRowInternalForeignKeys(orderType)); @@ -1192,7 +1192,7 @@ private static void AssertSprocs(IRelationalModel model, Mapping mapping, bool m var tableMapping = orderInsertMapping.TableMapping; if (mappedToTables) { - Assert.Equal("Order", tableMapping.Table.Name); + Assert.Equal("Order", tableMapping!.Table.Name); Assert.Same(orderInsertMapping, tableMapping.InsertStoredProcedureMapping); } else @@ -1200,12 +1200,12 @@ private static void AssertSprocs(IRelationalModel model, Mapping mapping, bool m Assert.Null(tableMapping); } - var billingAddressOwnership = orderDetailsType.FindNavigation(nameof(OrderDetails.BillingAddress)).ForeignKey; + var billingAddressOwnership = orderDetailsType.FindNavigation(nameof(OrderDetails.BillingAddress))!.ForeignKey; Assert.True(billingAddressOwnership.IsRequiredDependent); var billingAddressType = billingAddressOwnership.DeclaringEntityType; - var shippingAddressOwnership = orderDetailsType.FindNavigation(nameof(OrderDetails.ShippingAddress)).ForeignKey; + var shippingAddressOwnership = orderDetailsType.FindNavigation(nameof(OrderDetails.ShippingAddress))!.ForeignKey; Assert.True(shippingAddressOwnership.IsRequiredDependent); var billingAddressInsertMapping = billingAddressType.GetInsertStoredProcedureMappings().Single(); @@ -1310,7 +1310,7 @@ private static void AssertSprocs(IRelationalModel model, Mapping mapping, bool m Assert.False(customerDeleteSproc.IsOptional(extraSpecialCustomerType)); } - var customerPk = specialCustomerType.FindPrimaryKey(); + var customerPk = specialCustomerType.FindPrimaryKey()!; var idProperty = customerPk.Properties.Single(); if (mapping == Mapping.TPT) @@ -1786,7 +1786,7 @@ private static void AssertSprocs(IRelationalModel model, Mapping mapping, bool m Assert.Equal("Customer_Insert", customerInsertSproc.Name); Assert.Null(abstractCustomerType.GetInsertStoredProcedure()); - Assert.Equal("SpecialCustomer_Insert", specialCustomerType.GetInsertStoredProcedure().Name); + Assert.Equal("SpecialCustomer_Insert", specialCustomerType.GetInsertStoredProcedure()!.Name); Assert.False(specialCustomerInsertMapping.IncludesDerivedTypes); Assert.NotSame(customerInsertSproc, specialCustomerInsertSproc); @@ -2068,7 +2068,7 @@ private IRelationalModel CreateTestModel( if (mapping == Mapping.TPT) { cb.ToView(null); - cb.ToTable((string)null); + cb.ToTable((string?)null); } }); @@ -2479,9 +2479,9 @@ public void Can_use_relational_model_with_entity_splitting_and_table_splitting_o }); var model = Finalize(modelBuilder); - var customerType = model.Model.FindEntityType(typeof(SpecialCustomer)); + var customerType = model.Model.FindEntityType(typeof(SpecialCustomer))!; - var detailsNavigation = customerType.FindNavigation(nameof(SpecialCustomer.Details)); + var detailsNavigation = customerType.FindNavigation(nameof(SpecialCustomer.Details))!; var detailsType = detailsNavigation.TargetEntityType; Assert.Equal(2, model.Model.GetEntityTypes().Count()); @@ -2629,9 +2629,9 @@ public void Can_use_relational_model_with_entity_splitting_and_table_splitting_o }); var model = Finalize(modelBuilder); - var customerType = model.Model.FindEntityType(typeof(SpecialCustomer)); + var customerType = model.Model.FindEntityType(typeof(SpecialCustomer))!; - var detailsNavigation = customerType.FindNavigation(nameof(SpecialCustomer.Details)); + var detailsNavigation = customerType.FindNavigation(nameof(SpecialCustomer.Details))!; var detailsType = detailsNavigation.TargetEntityType; Assert.Equal(2, model.Model.GetEntityTypes().Count()); @@ -2745,9 +2745,9 @@ public void Can_use_relational_model_with_entity_splitting_and_table_splitting_o }); var model = Finalize(modelBuilder); - var customerType = model.Model.FindEntityType(typeof(SpecialCustomer)); + var customerType = model.Model.FindEntityType(typeof(SpecialCustomer))!; - var detailsNavigation = customerType.FindNavigation(nameof(SpecialCustomer.Details)); + var detailsNavigation = customerType.FindNavigation(nameof(SpecialCustomer.Details))!; var detailsType = detailsNavigation.TargetEntityType; Assert.Equal(2, model.Model.GetEntityTypes().Count()); @@ -2858,13 +2858,13 @@ public void Can_use_relational_model_with_keyless_TPH() Assert.Empty(model.Tables); Assert.Single(model.Views); - var customerType = model.Model.FindEntityType(typeof(Customer)); + var customerType = model.Model.FindEntityType(typeof(Customer))!; Assert.NotNull(customerType.FindDiscriminatorProperty()); var customerView = customerType.GetViewMappings().Single().View; Assert.Equal("CustomerView", customerView.Name); - var specialCustomerType = model.Model.FindEntityType(typeof(SpecialCustomer)); + var specialCustomerType = model.Model.FindEntityType(typeof(SpecialCustomer))!; var specialCustomerTypeMapping = specialCustomerType.GetViewMappings().Single(); Assert.Null(specialCustomerTypeMapping.IsSplitEntityTypePrincipal); @@ -2899,7 +2899,7 @@ public void Can_use_relational_model_with_tables_in_different_schemas() Assert.Equal(4, model.Model.GetEntityTypes().Count()); Assert.Empty(model.Views); - var orderDetails = model.Model.FindEntityType(typeof(OrderDetails)); + var orderDetails = model.Model.FindEntityType(typeof(OrderDetails))!; var orderDetailsTable = orderDetails.GetTableMappings().Single().Table; Assert.Equal(3, orderDetailsTable.ReferencingForeignKeyConstraints.Count()); } @@ -2928,7 +2928,7 @@ public void Can_use_relational_model_with_SQL_queries() Assert.Empty(model.Tables); Assert.Empty(model.Functions); - var orderType = model.Model.FindEntityType(typeof(Order)); + var orderType = model.Model.FindEntityType(typeof(Order))!; Assert.Null(orderType.FindPrimaryKey()); var orderMapping = orderType.GetSqlQueryMappings().Single(); @@ -2952,7 +2952,7 @@ public void Can_use_relational_model_with_SQL_queries() Assert.Equal("GetOrders()", ordersQuery.Sql); Assert.False(ordersQuery.IsShared); - var orderDate = orderType.FindProperty(nameof(Order.OrderDate)); + var orderDate = orderType.FindProperty(nameof(Order.OrderDate))!; Assert.Single(orderDate.GetSqlQueryColumnMappings()); var orderDateMapping = orderMapping.ColumnMappings.Single(m => m.Property == orderDate); Assert.NotNull(orderDateMapping.TypeMapping); @@ -2992,7 +2992,7 @@ public void Complex_property_container_column_type_is_used_in_relational_model() var model = Finalize(modelBuilder); - var entityType = model.Model.FindEntityType(typeof(EntityWithComplexProperty)); + var entityType = model.Model.FindEntityType(typeof(EntityWithComplexProperty))!; var complexProperty = entityType.GetComplexProperties().Single(); var complexType = complexProperty.ComplexType; @@ -3017,7 +3017,7 @@ public void Complex_collection_container_column_type_is_used_in_relational_model var model = Finalize(modelBuilder); - var entityType = model.Model.FindEntityType(typeof(EntityWithComplexCollection)); + var entityType = model.Model.FindEntityType(typeof(EntityWithComplexCollection))!; var complexProperty = entityType.GetComplexProperties().Single(); var complexType = complexProperty.ComplexType; @@ -3038,7 +3038,7 @@ public void Complex_property_gets_default_container_column_type_when_not_set_exp var model = Finalize(modelBuilder); - var entityType = model.Model.FindEntityType(typeof(EntityWithComplexProperty)); + var entityType = model.Model.FindEntityType(typeof(EntityWithComplexProperty))!; var complexProperty = entityType.GetComplexProperties().Single(); var complexType = complexProperty.ComplexType; @@ -3059,7 +3059,7 @@ public void Complex_collection_gets_default_container_column_type_when_not_set_e var model = Finalize(modelBuilder); - var entityType = model.Model.FindEntityType(typeof(EntityWithComplexCollection)); + var entityType = model.Model.FindEntityType(typeof(EntityWithComplexCollection))!; var complexProperty = entityType.GetComplexProperties().Single(); var complexType = complexProperty.ComplexType; @@ -3088,11 +3088,11 @@ public void Can_use_relational_model_with_functions() modelBuilder.HasDbFunction( typeof(RelationalModelTest).GetMethod( - nameof(GetOrdersForCustomer), BindingFlags.NonPublic | BindingFlags.Static, [typeof(int)])); + nameof(GetOrdersForCustomer), BindingFlags.NonPublic | BindingFlags.Static, [typeof(int)])!); modelBuilder.HasDbFunction( typeof(RelationalModelTest).GetMethod( - nameof(GetOrdersForCustomer), BindingFlags.NonPublic | BindingFlags.Static, [typeof(string)])); + nameof(GetOrdersForCustomer), BindingFlags.NonPublic | BindingFlags.Static, [typeof(string)])!); var model = Finalize(modelBuilder); @@ -3101,7 +3101,7 @@ public void Can_use_relational_model_with_functions() Assert.Empty(model.Views); Assert.Empty(model.Tables); - var orderType = model.Model.FindEntityType(typeof(Order)); + var orderType = model.Model.FindEntityType(typeof(Order))!; Assert.Null(orderType.FindPrimaryKey()); Assert.Equal(3, orderType.GetFunctionMappings().Count()); @@ -3139,7 +3139,7 @@ public void Can_use_relational_model_with_functions() Assert.False(ordersFunction.IsShared); Assert.Null(ordersFunction.ReturnType); - var orderDate = orderType.FindProperty(nameof(Order.OrderDate)); + var orderDate = orderType.FindProperty(nameof(Order.OrderDate))!; Assert.Equal(2, orderDate.GetFunctionColumnMappings().Count()); var orderDateMapping = orderMapping.ColumnMappings.Single(m => m.Property == orderDate); Assert.NotNull(orderDateMapping.TypeMapping); @@ -3193,8 +3193,8 @@ public void Can_use_relational_model_with_functions() public void Default_mappings_does_not_share_tableBase() { var modelBuilder = CreateConventionModelBuilder(); - modelBuilder.Entity().HasNoKey().ToTable((string)null); - modelBuilder.Entity().HasNoKey().ToTable((string)null); + modelBuilder.Entity().HasNoKey().ToTable((string?)null); + modelBuilder.Entity().HasNoKey().ToTable((string?)null); var model = Finalize(modelBuilder); @@ -3204,8 +3204,8 @@ public void Default_mappings_does_not_share_tableBase() Assert.Empty(model.Functions); Assert.Empty(model.Queries); - var entityType1 = model.Model.FindEntityType(typeof(SameEntityType)); - var entityType2 = model.Model.FindEntityType(typeof(NameSpace2.SameEntityType)); + var entityType1 = model.Model.FindEntityType(typeof(SameEntityType))!; + var entityType2 = model.Model.FindEntityType(typeof(NameSpace2.SameEntityType))!; var defaultMapping1 = Assert.Single(entityType1.GetDefaultMappings()); var defaultMapping2 = Assert.Single(entityType2.GetDefaultMappings()); @@ -3252,25 +3252,25 @@ public void GetQueryMappings_returns_in_priority_order_sql_query_function_view_t var model = Finalize(modelBuilder); // Table-only -> table mappings. - var orderType = model.Model.FindEntityType(typeof(Order)); + var orderType = model.Model.FindEntityType(typeof(Order))!; var orderMappings = orderType.GetQueryMappings().ToList(); Assert.Single(orderMappings); Assert.IsAssignableFrom(orderMappings[0]); // SqlQuery-only -> SQL query mappings. - var sqlQueryEntity = model.Model.FindEntityType(typeof(SameEntityType)); + var sqlQueryEntity = model.Model.FindEntityType(typeof(SameEntityType))!; var sqlQueryMappings = sqlQueryEntity.GetQueryMappings().ToList(); Assert.Single(sqlQueryMappings); Assert.IsAssignableFrom(sqlQueryMappings[0]); // Table + view -> view mappings win (lower-priority table mappings are not returned). - var viewAndTableEntity = model.Model.FindEntityType(typeof(NameSpace2.SameEntityType)); + var viewAndTableEntity = model.Model.FindEntityType(typeof(NameSpace2.SameEntityType))!; var viewAndTableMappings = viewAndTableEntity.GetQueryMappings().ToList(); Assert.Single(viewAndTableMappings); Assert.IsAssignableFrom(viewAndTableMappings[0]); // Function + view + table -> function mappings win (lower-priority view/table mappings are not returned). - var customerType = model.Model.FindEntityType(typeof(Customer)); + var customerType = model.Model.FindEntityType(typeof(Customer))!; var customerMappings = customerType.GetQueryMappings().ToList(); Assert.Single(customerMappings); Assert.IsAssignableFrom(customerMappings[0]); @@ -3809,11 +3809,11 @@ public void Can_use_relational_model_with_functions_and_json_owned_types() modelBuilder.HasDbFunction( typeof(RelationalModelTest).GetMethod( - nameof(GetOrdersForCustomer), BindingFlags.NonPublic | BindingFlags.Static, [typeof(int)])); + nameof(GetOrdersForCustomer), BindingFlags.NonPublic | BindingFlags.Static, [typeof(int)])!); var model = Finalize(modelBuilder); - var orderType = model.Model.FindEntityType(typeof(Order)); + var orderType = model.Model.FindEntityType(typeof(Order))!; var functionMappings = orderType.GetFunctionMappings().ToList(); Assert.Single(functionMappings); @@ -4006,41 +4006,39 @@ private enum MyEnum : ulong private abstract class AbstractBase { public int Id { get; set; } - public Tag Tag { get; set; } + public Tag Tag { get; set; } = null!; } public class Tag { - public string Name { get; set; } + public string Name { get; set; } = null!; } private class Customer : AbstractBase { - public string Name { get; set; } + public string Name { get; set; } = null!; public short SomeShort { get; set; } public MyEnum EnumValue { get; set; } - public IEnumerable Orders { get; set; } + public IEnumerable Orders { get; set; } = null!; } -#nullable enable private abstract class AbstractCustomer : Customer { public string AbstractString { get; set; } = null!; } -#nullable disable private class SpecialCustomer : AbstractCustomer { - public string Specialty { get; set; } - public string RelatedCustomerSpecialty { get; set; } - public SpecialCustomer RelatedCustomer { get; set; } - public CustomerDetails Details { get; set; } + public string Specialty { get; set; } = null!; + public string RelatedCustomerSpecialty { get; set; } = null!; + public SpecialCustomer RelatedCustomer { get; set; } = null!; + public CustomerDetails Details { get; set; } = null!; } private class CustomerDetails { - public string Address { get; set; } + public string Address { get; set; } = null!; // ReSharper disable once UnusedAutoPropertyAccessor.Local public DateTime BirthDay { get; set; } @@ -4054,30 +4052,30 @@ private class Order public Guid AlternateId { get; set; } public DateTime OrderDate { get; set; } - public DateDetails DateDetails { get; set; } + public DateDetails? DateDetails { get; set; } public int CustomerId { get; set; } - public Customer Customer { get; set; } + public Customer Customer { get; set; } = null!; - public OrderDetails Details { get; set; } + public OrderDetails? Details { get; set; } - public ComplexData ComplexProperty { get; set; } + public ComplexData? ComplexProperty { get; set; } - public List
Addresses { get; set; } + public List
Addresses { get; set; } = null!; } private class OrderDetails { public int OrderId { get; set; } - public Order Order { get; set; } + public Order Order { get; set; } = null!; public Guid AlternateId { get; set; } public bool Active { get; set; } public DateTime OrderDate { get; set; } - public DateDetails DateDetails { get; set; } + public DateDetails DateDetails { get; set; } = null!; - public Address BillingAddress { get; set; } - public Address ShippingAddress { get; set; } + public Address BillingAddress { get; set; } = null!; + public Address ShippingAddress { get; set; } = null!; } private class DateDetails @@ -4087,26 +4085,26 @@ private class DateDetails private class Address { - public string Street { get; set; } - public string City { get; set; } + public string Street { get; set; } = null!; + public string City { get; set; } = null!; } private class EntityWithComplexProperty { public int Id { get; set; } - public ComplexData ComplexProperty { get; set; } + public ComplexData? ComplexProperty { get; set; } } private class EntityWithComplexCollection { public int Id { get; set; } - public List ComplexCollection { get; set; } + public List ComplexCollection { get; set; } = null!; } private class EntityWithNestedComplexProperty { public int Id { get; set; } - public OuterComplexData ComplexProperty { get; set; } + public OuterComplexData ComplexProperty { get; set; } = null!; } private abstract class TphBaseEntity @@ -4118,13 +4116,13 @@ private class EntityWithoutComplexProperty : TphBaseEntity; private class TphEntityWithComplexProperty : TphBaseEntity { - public ComplexData ComplexProperty { get; set; } + public ComplexData ComplexProperty { get; set; } = null!; } private abstract class TptBaseEntityWithComplexProperty { public int Id { get; set; } - public ComplexData ComplexProperty { get; set; } + public ComplexData ComplexProperty { get; set; } = null!; } private class TptDerivedEntityWithoutComplexProperty : TptBaseEntityWithComplexProperty; @@ -4132,7 +4130,7 @@ private class TptDerivedEntityWithoutComplexProperty : TptBaseEntityWithComplexP private class TpcBaseEntityWithComplexProperty { public int Id { get; set; } - public ComplexData ComplexProperty { get; set; } + public ComplexData ComplexProperty { get; set; } = null!; } private class TpcDerivedEntityWithoutComplexProperty : TpcBaseEntityWithComplexProperty; @@ -4155,7 +4153,7 @@ private class TptDerivedWithComplexTypePK : TptBaseWithComplexTypePK private class EntityWithJsonOwnedWithCollection { public int Id { get; set; } - public JsonOwnedWithTags OwnedWithTags { get; set; } + public JsonOwnedWithTags OwnedWithTags { get; set; } = null!; } private enum PrimitiveCollectionEnum @@ -4166,23 +4164,23 @@ private enum PrimitiveCollectionEnum private class JsonOwnedWithTags { - public string Label { get; set; } - public List Tags { get; set; } - public List EnumValues { get; set; } + public string Label { get; set; } = null!; + public List Tags { get; set; } = null!; + public List EnumValues { get; set; } = null!; } [ComplexType] private class ComplexData { - public string Value { get; set; } + public string? Value { get; set; } public int Number { get; set; } } [ComplexType] private class OuterComplexData { - public string Value { get; set; } - public NestedComplexData Nested { get; set; } + public string Value { get; set; } = null!; + public NestedComplexData Nested { get; set; } = null!; } [ComplexType] diff --git a/test/EFCore.Relational.Tests/Metadata/RelationalPropertyAttributeConventionTest.cs b/test/EFCore.Relational.Tests/Metadata/RelationalPropertyAttributeConventionTest.cs index 54c2a875e00..bbb9dc5188c 100644 --- a/test/EFCore.Relational.Tests/Metadata/RelationalPropertyAttributeConventionTest.cs +++ b/test/EFCore.Relational.Tests/Metadata/RelationalPropertyAttributeConventionTest.cs @@ -59,7 +59,7 @@ public void ColumnAttribute_overrides_configuration_from_convention_source() { var entityBuilder = CreateInternalEntityTypeBuilder(); - var propertyBuilder = entityBuilder.Property(typeof(string), "Name", ConfigurationSource.Explicit); + var propertyBuilder = entityBuilder.Property(typeof(string), "Name", ConfigurationSource.Explicit)!; propertyBuilder.HasAnnotation(RelationalAnnotationNames.ColumnName, "ConventionalName", ConfigurationSource.Convention); propertyBuilder.HasAnnotation(RelationalAnnotationNames.ColumnType, "BYTE", ConfigurationSource.Convention); @@ -79,7 +79,7 @@ public void CommentAttribute_overrides_configuration_from_convention_source() { var entityBuilder = CreateInternalEntityTypeBuilder(); - var propertyBuilder = entityBuilder.Property(typeof(string), "Name", ConfigurationSource.Explicit); + var propertyBuilder = entityBuilder.Property(typeof(string), "Name", ConfigurationSource.Explicit)!; propertyBuilder.HasAnnotation(RelationalAnnotationNames.Comment, "ConventionalName", ConfigurationSource.Convention); @@ -93,7 +93,7 @@ public void ColumnAttribute_does_not_override_configuration_from_explicit_source { var entityBuilder = CreateInternalEntityTypeBuilder(); - var propertyBuilder = entityBuilder.Property(typeof(string), "Name", ConfigurationSource.Explicit); + var propertyBuilder = entityBuilder.Property(typeof(string), "Name", ConfigurationSource.Explicit)!; propertyBuilder.HasAnnotation(RelationalAnnotationNames.ColumnName, "ExplicitName", ConfigurationSource.Explicit); propertyBuilder.HasAnnotation(RelationalAnnotationNames.ColumnType, "BYTE", ConfigurationSource.Explicit); @@ -113,7 +113,7 @@ public void CommentAttribute_does_not_override_configuration_from_explicit_sourc { var entityBuilder = CreateInternalEntityTypeBuilder(); - var propertyBuilder = entityBuilder.Property(typeof(string), "Name", ConfigurationSource.Explicit); + var propertyBuilder = entityBuilder.Property(typeof(string), "Name", ConfigurationSource.Explicit)!; propertyBuilder.HasAnnotation(RelationalAnnotationNames.Comment, "ExplicitComment", ConfigurationSource.Explicit); @@ -142,7 +142,7 @@ private InternalEntityTypeBuilder CreateInternalEntityTypeBuilder() var modelBuilder = new Model(conventionSet).Builder; - return modelBuilder.Entity(typeof(T), ConfigurationSource.Explicit); + return modelBuilder.Entity(typeof(T), ConfigurationSource.Explicit)!; } private ProviderConventionSetBuilderDependencies CreateDependencies() @@ -159,7 +159,7 @@ private class A public int Id { get; set; } [Column("Post Name", Order = 1, TypeName = "DECIMAL"), Comment("Test column comment")] - public string Name { get; set; } + public string Name { get; set; } = null!; } public class F @@ -167,6 +167,6 @@ public class F public int Id { get; set; } [Column("Post Name", Order = 1, TypeName = "DECIMAL"), Comment("Test column comment")] - public string Name; + public string Name = null!; } } diff --git a/test/EFCore.Relational.Tests/Metadata/TriggerTest.cs b/test/EFCore.Relational.Tests/Metadata/TriggerTest.cs index 19bd8eaf61b..6f83f5a87a3 100644 --- a/test/EFCore.Relational.Tests/Metadata/TriggerTest.cs +++ b/test/EFCore.Relational.Tests/Metadata/TriggerTest.cs @@ -85,6 +85,6 @@ protected virtual ModelBuilder CreateConventionModelBuilder() private class Customer { public int Id { get; set; } - public string Name { get; set; } + public string Name { get; set; } = null!; } } diff --git a/test/EFCore.Relational.Tests/Migrations/Internal/MigrationsAssemblyTest.cs b/test/EFCore.Relational.Tests/Migrations/Internal/MigrationsAssemblyTest.cs index da5f98e9f9c..098dda60830 100644 --- a/test/EFCore.Relational.Tests/Migrations/Internal/MigrationsAssemblyTest.cs +++ b/test/EFCore.Relational.Tests/Migrations/Internal/MigrationsAssemblyTest.cs @@ -48,7 +48,7 @@ public void Migrations_ignores_the_unattributed() } private IMigrationsAssembly CreateMigrationsAssembly( - IDiagnosticsLogger logger = null) + IDiagnosticsLogger? logger = null) => new MigrationsAssembly( new CurrentDbContext(new Context()), new DbContextOptions( diff --git a/test/EFCore.Relational.Tests/Migrations/Internal/MigrationsModelDifferTest.cs b/test/EFCore.Relational.Tests/Migrations/Internal/MigrationsModelDifferTest.cs index 0265a21f787..2000ec30867 100644 --- a/test/EFCore.Relational.Tests/Migrations/Internal/MigrationsModelDifferTest.cs +++ b/test/EFCore.Relational.Tests/Migrations/Internal/MigrationsModelDifferTest.cs @@ -322,40 +322,40 @@ private class Book { public int Id { get; set; } - public Album Album { get; set; } - public User User { get; set; } - public ICollection Albums { get; set; } - public ICollection Users { get; set; } + public Album Album { get; set; } = null!; + public User User { get; set; } = null!; + public ICollection Albums { get; set; } = null!; + public ICollection Users { get; set; } = null!; } private class Album { public int Id { get; set; } - public User OwnerUser { get; set; } - public Book Book { get; set; } - public ICollection Books { get; set; } - public ICollection Groups { get; set; } + public User OwnerUser { get; set; } = null!; + public Book Book { get; set; } = null!; + public ICollection Books { get; set; } = null!; + public ICollection Groups { get; set; } = null!; } private class User { public int Id { get; set; } - public Book Book { get; set; } - public Group ReaderGroup { get; set; } - public ICollection AlbumOwnerUsers { get; set; } - public ICollection Books { get; set; } - public ICollection Groups { get; set; } + public Book Book { get; set; } = null!; + public Group ReaderGroup { get; set; } = null!; + public ICollection AlbumOwnerUsers { get; set; } = null!; + public ICollection Books { get; set; } = null!; + public ICollection Groups { get; set; } = null!; } private class Group { public int Id { get; set; } - public Album OwnerAlbum { get; set; } - public User OwnerUser { get; set; } - public ICollection UserReaderGroups { get; set; } + public Album OwnerAlbum { get; set; } = null!; + public User OwnerUser { get; set; } = null!; + public ICollection UserReaderGroups { get; set; } = null!; } [Fact] @@ -416,7 +416,7 @@ private class CreateTableEntity2 { public int Id { get; set; } public int E { get; set; } - public CreateTableEntity2B D { get; set; } + public CreateTableEntity2B D { get; set; } = null!; public int A { get; set; } } @@ -1103,7 +1103,7 @@ public void Create_shared_table_with_two_types() var createTableOperation = Assert.IsType(upOps[0]); Assert.Equal("Animal", createTableOperation.Name); - Assert.Equal("Id", createTableOperation.PrimaryKey.Columns.Single()); + Assert.Equal("Id", createTableOperation.PrimaryKey!.Columns.Single()); Assert.Equal(["Id", "MouseId", "BoneId"], createTableOperation.Columns.Select(c => c.Name)); Assert.Empty(createTableOperation.ForeignKeys); Assert.Empty(createTableOperation.UniqueConstraints); @@ -1331,7 +1331,7 @@ public void Can_add_tables_with_entity_splitting_with_seed_data() { var m = Assert.IsType(o); Assert.Equal("Animal", m.Name); - Assert.Equal("Id", m.PrimaryKey.Columns.Single()); + Assert.Equal("Id", m.PrimaryKey!.Columns.Single()); Assert.Equal(["Id", "MouseId"], m.Columns.Select(c => c.Name)); Assert.Empty(m.ForeignKeys); }, @@ -1339,7 +1339,7 @@ public void Can_add_tables_with_entity_splitting_with_seed_data() { var m = Assert.IsType(o); Assert.Equal("AnimalDetails", m.Name); - Assert.Equal("Id", m.PrimaryKey.Columns.Single()); + Assert.Equal("Id", m.PrimaryKey!.Columns.Single()); Assert.Equal(["Id", "BoneId"], m.Columns.Select(c => c.Name)); var fk = m.ForeignKeys.Single(); Assert.Equal("Animal", fk.PrincipalTable); @@ -2376,7 +2376,7 @@ public void Rename_property_and_column() public void Rename_property_and_column_when_snapshot() => Execute( source => source.Entity( - typeof(Crab).FullName, + typeof(Crab).FullName!, x => { x.ToTable("Crab"); @@ -2544,7 +2544,7 @@ public void Rename_column_in_TPT_with_table_sharing_and_seed_data() private class Crab { - public string Id { get; set; } + public string Id { get; set; } = null!; } [Fact] @@ -6272,7 +6272,7 @@ public void Change_TPH_to_TPT_with_FKs_and_seed_data() Assert.Null(c.Collation); }); - var pk = operation.PrimaryKey; + var pk = operation.PrimaryKey!; Assert.Equal("PK_Cats", pk.Name); Assert.Equal("Cats", pk.Table); Assert.Equal(new[] { "Id" }, pk.Columns); @@ -6328,7 +6328,7 @@ public void Change_TPH_to_TPT_with_FKs_and_seed_data() Assert.Null(c.Collation); }); - var pk = operation.PrimaryKey; + var pk = operation.PrimaryKey!; Assert.Equal("PK_Mice", pk.Name); Assert.Equal("Mice", pk.Table); Assert.Equal(new[] { "Id" }, pk.Columns); @@ -6913,7 +6913,7 @@ public void Change_TPH_to_TPT_with_FKs_and_seed_data_readonly_discriminator() Assert.Null(c.Collation); }); - var pk = operation.PrimaryKey; + var pk = operation.PrimaryKey!; Assert.Equal("PK_Cats", pk.Name); Assert.Equal("Cats", pk.Table); Assert.Equal(new[] { "Id" }, pk.Columns); @@ -6969,7 +6969,7 @@ public void Change_TPH_to_TPT_with_FKs_and_seed_data_readonly_discriminator() Assert.Null(c.Collation); }); - var pk = operation.PrimaryKey; + var pk = operation.PrimaryKey!; Assert.Equal("PK_Mice", pk.Name); Assert.Equal("Mice", pk.Table); Assert.Equal(new[] { "Id" }, pk.Columns); @@ -7613,7 +7613,7 @@ public void Change_TPH_to_TPC_with_FKs_and_seed_data() Assert.True(c.IsNullable); }); - var pk = operation.PrimaryKey; + var pk = operation.PrimaryKey!; Assert.Equal("PK_Mice", pk.Name); Assert.Equal("Mice", pk.Table); Assert.Equal(new[] { "Id" }, pk.Columns); @@ -7658,7 +7658,7 @@ public void Change_TPH_to_TPC_with_FKs_and_seed_data() Assert.True(c.IsNullable); }); - var pk = operation.PrimaryKey; + var pk = operation.PrimaryKey!; Assert.Equal("PK_Cats", pk.Name); Assert.Equal("Cats", pk.Table); Assert.Equal(new[] { "Id" }, pk.Columns); @@ -8995,7 +8995,7 @@ public void Split_out_subtype_with_seed_data() private class Animal { public int Id { get; set; } - public string Name { get; set; } + public string Name { get; set; } = null!; } private class Eagle : Animal; @@ -10056,7 +10056,7 @@ public void Owned_collection_with_explicit_id() public class Account { - public string Id { get; set; } + public string Id { get; set; } = null!; public IEnumerable AccountHolders { get; set; } = []; } @@ -10379,10 +10379,10 @@ public void Noop_on_complex_collection_property_annotations_not_in_snapshot() protected class MyJsonComplex { - public string Value { get; set; } + public string Value { get; set; } = null!; public DateTime Date { get; set; } - public MyNestedComplex Nested { get; set; } - public List NestedCollection { get; set; } + public MyNestedComplex Nested { get; set; } = null!; + public List NestedCollection { get; set; } = null!; } protected class MyNestedComplex @@ -10677,8 +10677,8 @@ public void SeedData_binary_change_custom_comparer() private class RightmostValueComparer() : ValueComparer(false) { - public override bool Equals(byte[] left, byte[] right) - => object.Equals(left[^1], right[^1]); + public override bool Equals(byte[]? left, byte[]? right) + => object.Equals(left![^1], right![^1]); } [Fact] @@ -11033,7 +11033,7 @@ public void SeedData_change_enum_conversion() target => target.Entity( "EntityWithEnumProperty", x => x.Property("Enum") - .HasConversion(e => e.ToString(), e => (SomeEnum)Enum.Parse(typeof(SomeEnum), e))), + .HasConversion(e => e.ToString(), e => (SomeEnum)Enum.Parse(typeof(SomeEnum), e!))), upOps => Assert.Collection( upOps, o => @@ -11753,10 +11753,10 @@ private class OldOrder { public int Id { get; set; } - public string AddressLine1 { get; set; } - public string AddressLine2 { get; set; } + public string? AddressLine1 { get; set; } + public string? AddressLine2 { get; set; } - public Address Billing { get; set; } + public Address? Billing { get; set; } } private class Order @@ -11772,22 +11772,22 @@ public Order(int secretId) public int Id { get; set; } - public Address Billing { get; set; } - public Address Shipping { get; set; } + public Address? Billing { get; set; } + public Address? Shipping { get; set; } } private class Customer { public int Id { get; set; } - public Address Mailing { get; set; } - public ICollection Orders { get; set; } + public Address Mailing { get; set; } = null!; + public ICollection Orders { get; set; } = null!; } private class Address { - public string AddressLine1 { get; set; } - public string AddressLine2 { get; set; } + public string? AddressLine1 { get; set; } + public string? AddressLine2 { get; set; } } [Fact] @@ -12004,15 +12004,15 @@ public void SeedData_type_with_excluded_owned_collection() public class Parent { public Guid Id { get; set; } - public string Name { get; set; } + public string Name { get; set; } = null!; - public IEnumerable Children { get; set; } + public IEnumerable Children { get; set; } = null!; } public class Child { public Guid Id { get; set; } - public string ChildName { get; set; } + public string ChildName { get; set; } = null!; } [Fact] @@ -12166,7 +12166,7 @@ public void Change_default_schema_with_owned_entities() target.Entity( "Order", b => b.OwnsOne( - "OrderInfo", "OrderInfo", b1 => b1.ToTable("Order", (string)null))); + "OrderInfo", "OrderInfo", b1 => b1.ToTable("Order", (string?)null))); }, Assert.Empty, Assert.Empty); @@ -12385,12 +12385,12 @@ public void Alter_database_collation() public class Customer13300 : ProviderTenantEntity13300 { - public string DisplayName { get; set; } + public string DisplayName { get; set; } = null!; } public abstract class ProviderTenantEntity13300 : TenantEntity13300 { - public string ProviderKey { get; set; } + public string ProviderKey { get; set; } = null!; } public abstract class TenantEntity13300 @@ -12401,7 +12401,7 @@ public abstract class TenantEntity13300 public class ReferencePoint13300 { - public string Reason { get; set; } + public string Reason { get; set; } = null!; } [Fact] @@ -12438,8 +12438,8 @@ var dependentTableCreation public abstract class Base { public int? RealFkNavigationId { get; set; } - public Principal ShadowFkNavigation { get; set; } - public Principal RealFkNavigation { get; set; } + public Principal ShadowFkNavigation { get; set; } = null!; + public Principal RealFkNavigation { get; set; } = null!; public int Id3 { get; set; } } @@ -12447,7 +12447,7 @@ public class Dependent : Base { public int Id2 { get; set; } public int Id1 { get; set; } - public string Value { get; set; } + public string Value { get; set; } = null!; } public class Principal @@ -12457,7 +12457,7 @@ public class Principal private class Blog { - private readonly Action _loader; + private readonly Action _loader = null!; public Blog() { @@ -12467,18 +12467,18 @@ private Blog(Action lazyLoader) => _loader = lazyLoader; public int BlogId { get; set; } - public string Url { get; set; } + public string? Url { get; set; } public ICollection Posts { - get => _loader.Load(this, ref field); + get => _loader.Load(this, ref field)!; set; - } + } = null!; } private class Post { - private readonly ILazyLoader _loader; + private readonly ILazyLoader _loader = null!; public Post() { @@ -12488,10 +12488,10 @@ private Post(ILazyLoader loader) => _loader = loader; public int PostId { get; set; } - public string Title { get; set; } + public string? Title { get; set; } public int? BlogId { get; set; } - public Blog Blog + public Blog? Blog { get => _loader.Load(this, ref field); set; @@ -12767,7 +12767,7 @@ public void Construction_of_shadow_values_buffer_account_for_shadow_navigations_ private class TestKeylessType { - public string Something { get; set; } + public string Something { get; set; } = null!; } private static IQueryable GetCountByYear(int id) @@ -12782,7 +12782,7 @@ public void Model_differ_does_not_detect_entity_type_mapped_to_TVF() var function = modelBuilder.HasDbFunction( typeof(MigrationsModelDifferTest).GetMethod( nameof(GetCountByYear), - BindingFlags.NonPublic | BindingFlags.Static)).Metadata; + BindingFlags.NonPublic | BindingFlags.Static)!).Metadata; modelBuilder.Entity().ToFunction(function.ModelName); }, diff --git a/test/EFCore.Relational.Tests/Migrations/Internal/MigrationsModelDifferTestBase.cs b/test/EFCore.Relational.Tests/Migrations/Internal/MigrationsModelDifferTestBase.cs index 5780c75d792..0db4aa9c768 100644 --- a/test/EFCore.Relational.Tests/Migrations/Internal/MigrationsModelDifferTestBase.cs +++ b/test/EFCore.Relational.Tests/Migrations/Internal/MigrationsModelDifferTestBase.cs @@ -27,7 +27,7 @@ protected void Execute( Action buildSourceAction, Action buildTargetAction, Action> assertActionUp, - Action> assertActionDown, + Action>? assertActionDown, bool skipSourceConventions = false) => Execute( buildCommonAction, buildSourceAction, buildTargetAction, assertActionUp, assertActionDown, null, skipSourceConventions); @@ -37,8 +37,8 @@ protected void Execute( Action buildSourceAction, Action buildTargetAction, Action> assertActionUp, - Action> assertActionDown, - Action builderOptionsAction, + Action>? assertActionDown, + Action? builderOptionsAction, bool skipSourceConventions = false, bool enableSensitiveLogging = true) { diff --git a/test/EFCore.Relational.Tests/Migrations/MigrationCommandExecutorTest.cs b/test/EFCore.Relational.Tests/Migrations/MigrationCommandExecutorTest.cs index 1906ceb2f41..45e66416980 100644 --- a/test/EFCore.Relational.Tests/Migrations/MigrationCommandExecutorTest.cs +++ b/test/EFCore.Relational.Tests/Migrations/MigrationCommandExecutorTest.cs @@ -362,10 +362,10 @@ private static IMigrationCommandExecutor CreateMigrationCommandExecutor() private const string ConnectionString = "Fake Connection String"; - private static FakeRelationalConnection CreateConnection(IDbContextOptions options = null) + private static FakeRelationalConnection CreateConnection(IDbContextOptions? options = null) => new(options ?? CreateOptions()); - private static IDbContextOptions CreateOptions(RelationalOptionsExtension optionsExtension = null) + private static IDbContextOptions CreateOptions(RelationalOptionsExtension? optionsExtension = null) { var optionsBuilder = new DbContextOptionsBuilder(); @@ -380,7 +380,7 @@ private static IDbContextOptions CreateOptions(RelationalOptionsExtension option private IRelationalCommand CreateRelationalCommand( string commandText = "Command Text", string logCommandText = "Log Command Text", - IReadOnlyList parameters = null) + IReadOnlyList? parameters = null) => new RelationalCommand( new RelationalCommandBuilderDependencies( new TestRelationalTypeMappingSource( diff --git a/test/EFCore.Relational.Tests/Query/Internal/BufferedDataReaderTest.cs b/test/EFCore.Relational.Tests/Query/Internal/BufferedDataReaderTest.cs index 91fdbdec12f..c673a1554aa 100644 --- a/test/EFCore.Relational.Tests/Query/Internal/BufferedDataReaderTest.cs +++ b/test/EFCore.Relational.Tests/Query/Internal/BufferedDataReaderTest.cs @@ -177,7 +177,7 @@ private async Task Verify_method_result( columnType = typeof(object); } - var getFieldValueMethod = typeof(DbDataReader).GetMethod(nameof(DbDataReader.GetFieldValue)).MakeGenericMethod(columnType); + var getFieldValueMethod = typeof(DbDataReader).GetMethod(nameof(DbDataReader.GetFieldValue))!.MakeGenericMethod(columnType); var prm = Expression.Parameter(typeof(DbDataReader), "r"); var getFieldValueLambda = Expression.Lambda( Expression.Call(prm, getFieldValueMethod, Expression.Constant(0)), @@ -213,7 +213,7 @@ private Task Verify_get_method_returns_supplied_value(T value, bool async) // use the specific reader.GetXXX method var readerMethod = GetReaderMethod(typeof(T)); return Verify_method_result( - r => (T)readerMethod.Invoke(r, [0]), async, value, [value]); + r => (T)readerMethod.Invoke(r, [0])!, async, value, [value!]); } private static MethodInfo GetReaderMethod(Type type) diff --git a/test/EFCore.Relational.Tests/RelationalApiConsistencyTest.cs b/test/EFCore.Relational.Tests/RelationalApiConsistencyTest.cs index 375f4598c25..f7e9d9143f8 100644 --- a/test/EFCore.Relational.Tests/RelationalApiConsistencyTest.cs +++ b/test/EFCore.Relational.Tests/RelationalApiConsistencyTest.cs @@ -80,13 +80,13 @@ public class RelationalApiConsistencyFixture : ApiConsistencyFixtureBase { typeof(IReadOnlyEntityTypeMappingFragment), (typeof(IMutableEntityTypeMappingFragment), typeof(IConventionEntityTypeMappingFragment), - null, + null!, typeof(IEntityTypeMappingFragment)) }, { typeof(IReadOnlyRelationalPropertyOverrides), (typeof(IMutableRelationalPropertyOverrides), typeof(IConventionRelationalPropertyOverrides), - null, + null!, typeof(IRelationalPropertyOverrides)) } }; @@ -190,7 +190,7 @@ public class RelationalApiConsistencyFixture : ApiConsistencyFixtureBase typeof(RelationalModelExtensions), typeof(RelationalModelExtensions), typeof(RelationalModelBuilderExtensions), - null + null! ) }, { @@ -199,7 +199,7 @@ public class RelationalApiConsistencyFixture : ApiConsistencyFixtureBase typeof(RelationalEntityTypeExtensions), typeof(RelationalEntityTypeExtensions), typeof(RelationalEntityTypeBuilderExtensions), - null + null! ) }, { @@ -207,17 +207,17 @@ public class RelationalApiConsistencyFixture : ApiConsistencyFixtureBase typeof(RelationalTypeBaseExtensions), typeof(RelationalTypeBaseExtensions), typeof(RelationalTypeBaseExtensions), - null, - null + null!, + null! ) }, { typeof(IReadOnlyTypeBase), ( - null, - null, - null, - null, - null + null!, + null!, + null!, + null!, + null! ) }, { @@ -226,7 +226,7 @@ public class RelationalApiConsistencyFixture : ApiConsistencyFixtureBase typeof(RelationalKeyExtensions), typeof(RelationalKeyExtensions), typeof(RelationalKeyBuilderExtensions), - null + null! ) }, { @@ -235,16 +235,16 @@ public class RelationalApiConsistencyFixture : ApiConsistencyFixtureBase typeof(RelationalForeignKeyExtensions), typeof(RelationalForeignKeyExtensions), typeof(RelationalForeignKeyBuilderExtensions), - null + null! ) }, { typeof(IReadOnlyComplexProperty), ( - null, - null, - null, - null, - null + null!, + null!, + null!, + null!, + null! ) }, { @@ -253,7 +253,7 @@ public class RelationalApiConsistencyFixture : ApiConsistencyFixtureBase typeof(RelationalPropertyExtensions), typeof(RelationalPropertyExtensions), typeof(RelationalPropertyBuilderExtensions), - null + null! ) }, { @@ -262,7 +262,7 @@ public class RelationalApiConsistencyFixture : ApiConsistencyFixtureBase typeof(RelationalIndexExtensions), typeof(RelationalIndexExtensions), typeof(RelationalIndexBuilderExtensions), - null + null! ) }, { @@ -271,7 +271,7 @@ public class RelationalApiConsistencyFixture : ApiConsistencyFixtureBase typeof(RelationalTriggerExtensions), typeof(RelationalTriggerExtensions), typeof(RelationalTriggerBuilderExtensions), - null + null! ) }, { @@ -279,17 +279,17 @@ public class RelationalApiConsistencyFixture : ApiConsistencyFixtureBase typeof(RelationalDbFunctionsExtensions), typeof(RelationalDbFunctionsExtensions), typeof(RelationalDbFunctionsExtensions), - null, - null + null!, + null! ) }, { typeof(IReadOnlyElementType), ( typeof(RelationalElementTypeExtensions), - null, - null, + null!, + null!, typeof(RelationalEntityTypeBuilderExtensions), - null + null! ) } }; @@ -306,16 +306,16 @@ public class RelationalApiConsistencyFixture : ApiConsistencyFixtureBase public override HashSet UnmatchedMetadataMethods { get; } = [ typeof(RelationalEntityTypeBuilderExtensions).GetMethod( - nameof(RelationalEntityTypeBuilderExtensions.ExcludeTableFromMigrations)), + nameof(RelationalEntityTypeBuilderExtensions.ExcludeTableFromMigrations))!, typeof(RelationalIndexBuilderExtensions).GetMethod( nameof(RelationalIndexBuilderExtensions.HasName), - [typeof(IndexBuilder), typeof(string)]), + [typeof(IndexBuilder), typeof(string)])!, typeof(RelationalPropertyExtensions).GetMethod( nameof(RelationalPropertyExtensions.FindOverrides), - [typeof(IReadOnlyProperty), typeof(StoreObjectIdentifier).MakeByRefType()]), + [typeof(IReadOnlyProperty), typeof(StoreObjectIdentifier).MakeByRefType()])!, typeof(RelationalPropertyExtensions).GetMethod( nameof(RelationalPropertyExtensions.GetOverrides), - [typeof(IReadOnlyProperty)]), + [typeof(IReadOnlyProperty)])!, GetMethod( typeof(StoredProcedureBuilder<>), nameof(StoredProcedureBuilder.HasParameter), @@ -369,18 +369,18 @@ public class RelationalApiConsistencyFixture : ApiConsistencyFixtureBase ]), typeof(IConventionStoredProcedure).GetMethod( nameof(IConventionStoredProcedure.SetIsRowsAffectedReturned), - [typeof(bool), typeof(bool)]) + [typeof(bool), typeof(bool)])! ]; public override Dictionary> UnmatchedMirrorMethods { get; } = new() { { typeof(PrimitiveCollectionBuilder), [ - typeof(PropertyBuilder).GetMethod(nameof(PropertyBuilder.HasPrecision), [typeof(int)]), - typeof(PropertyBuilder).GetMethod(nameof(PropertyBuilder.HasPrecision), [typeof(int), typeof(int)]), + typeof(PropertyBuilder).GetMethod(nameof(PropertyBuilder.HasPrecision), [typeof(int)])!, + typeof(PropertyBuilder).GetMethod(nameof(PropertyBuilder.HasPrecision), [typeof(int), typeof(int)])!, typeof(PropertyBuilder).GetMethod( - nameof(PropertyBuilder.HasValueGenerator), [typeof(Func)]), - typeof(PropertyBuilder).GetMethod(nameof(PropertyBuilder.IsRowVersion), Type.EmptyTypes), + nameof(PropertyBuilder.HasValueGenerator), [typeof(Func)])!, + typeof(PropertyBuilder).GetMethod(nameof(PropertyBuilder.IsRowVersion), Type.EmptyTypes)!, GetMethod( typeof(PropertyBuilder), nameof(PropertyBuilder.HasConversion), genericParameterCount: 1, (_, _) => Type.EmptyTypes), @@ -396,31 +396,31 @@ public class RelationalApiConsistencyFixture : ApiConsistencyFixtureBase GetMethod( typeof(PropertyBuilder), nameof(PropertyBuilder.HasConversion), genericParameterCount: 1, (_, _) => [typeof(ValueComparer), typeof(ValueComparer)]), - typeof(PropertyBuilder).GetMethod(nameof(PropertyBuilder.HasConversion), [typeof(Type)]), - typeof(PropertyBuilder).GetMethod(nameof(PropertyBuilder.HasConversion), [typeof(ValueComparer)]), - typeof(PropertyBuilder).GetMethod(nameof(PropertyBuilder.HasConversion), [typeof(ValueConverter)]), + typeof(PropertyBuilder).GetMethod(nameof(PropertyBuilder.HasConversion), [typeof(Type)])!, + typeof(PropertyBuilder).GetMethod(nameof(PropertyBuilder.HasConversion), [typeof(ValueComparer)])!, + typeof(PropertyBuilder).GetMethod(nameof(PropertyBuilder.HasConversion), [typeof(ValueConverter)])!, typeof(PropertyBuilder).GetMethod( - nameof(PropertyBuilder.HasConversion), [typeof(ValueComparer), typeof(ValueComparer)]), - typeof(PropertyBuilder).GetMethod(nameof(PropertyBuilder.HasConversion), [typeof(Type), typeof(ValueComparer)]), + nameof(PropertyBuilder.HasConversion), [typeof(ValueComparer), typeof(ValueComparer)])!, + typeof(PropertyBuilder).GetMethod(nameof(PropertyBuilder.HasConversion), [typeof(Type), typeof(ValueComparer)])!, typeof(PropertyBuilder).GetMethod( - nameof(PropertyBuilder.HasConversion), [typeof(Type), typeof(ValueComparer), typeof(ValueComparer)]), + nameof(PropertyBuilder.HasConversion), [typeof(Type), typeof(ValueComparer), typeof(ValueComparer)])!, typeof(PropertyBuilder).GetMethod( - nameof(PropertyBuilder.HasConversion), [typeof(ValueConverter), typeof(ValueComparer)]), + nameof(PropertyBuilder.HasConversion), [typeof(ValueConverter), typeof(ValueComparer)])!, typeof(PropertyBuilder).GetMethod( nameof(PropertyBuilder.HasConversion), - [typeof(ValueConverter), typeof(ValueComparer), typeof(ValueComparer)]), - typeof(PropertyBuilder).GetMethod(nameof(PropertyBuilder.HasConversion), [typeof(Type), typeof(Type)]), + [typeof(ValueConverter), typeof(ValueComparer), typeof(ValueComparer)])!, + typeof(PropertyBuilder).GetMethod(nameof(PropertyBuilder.HasConversion), [typeof(Type), typeof(Type)])!, typeof(PropertyBuilder).GetMethod( - nameof(PropertyBuilder.HasConversion), [typeof(Type), typeof(Type), typeof(Type)]) + nameof(PropertyBuilder.HasConversion), [typeof(Type), typeof(Type), typeof(Type)])! ] }, { typeof(PrimitiveCollectionBuilder<>), [ - typeof(PropertyBuilder<>).GetMethod(nameof(PropertyBuilder.HasPrecision), [typeof(int)]), - typeof(PropertyBuilder<>).GetMethod(nameof(PropertyBuilder.HasPrecision), [typeof(int), typeof(int)]), + typeof(PropertyBuilder<>).GetMethod(nameof(PropertyBuilder.HasPrecision), [typeof(int)])!, + typeof(PropertyBuilder<>).GetMethod(nameof(PropertyBuilder.HasPrecision), [typeof(int), typeof(int)])!, typeof(PropertyBuilder<>).GetMethod( - nameof(PropertyBuilder.HasValueGenerator), [typeof(Func)]), - typeof(PropertyBuilder<>).GetMethod(nameof(PropertyBuilder.IsRowVersion), Type.EmptyTypes), + nameof(PropertyBuilder.HasValueGenerator), [typeof(Func)])!, + typeof(PropertyBuilder<>).GetMethod(nameof(PropertyBuilder.IsRowVersion), Type.EmptyTypes)!, GetMethod( typeof(PropertyBuilder<>), nameof(PropertyBuilder.HasConversion), genericParameterCount: 1, (_, _) => Type.EmptyTypes), @@ -436,25 +436,25 @@ public class RelationalApiConsistencyFixture : ApiConsistencyFixtureBase GetMethod( typeof(PropertyBuilder<>), nameof(PropertyBuilder.HasConversion), genericParameterCount: 1, (_, _) => [typeof(ValueComparer), typeof(ValueComparer)]), - typeof(PropertyBuilder<>).GetMethod(nameof(PropertyBuilder.HasConversion), [typeof(Type)]), - typeof(PropertyBuilder<>).GetMethod(nameof(PropertyBuilder.HasConversion), [typeof(ValueComparer)]), - typeof(PropertyBuilder<>).GetMethod(nameof(PropertyBuilder.HasConversion), [typeof(ValueConverter)]), + typeof(PropertyBuilder<>).GetMethod(nameof(PropertyBuilder.HasConversion), [typeof(Type)])!, + typeof(PropertyBuilder<>).GetMethod(nameof(PropertyBuilder.HasConversion), [typeof(ValueComparer)])!, + typeof(PropertyBuilder<>).GetMethod(nameof(PropertyBuilder.HasConversion), [typeof(ValueConverter)])!, typeof(PropertyBuilder<>).GetMethod( - nameof(PropertyBuilder.HasConversion), [typeof(ValueComparer), typeof(ValueComparer)]), + nameof(PropertyBuilder.HasConversion), [typeof(ValueComparer), typeof(ValueComparer)])!, typeof(PropertyBuilder<>).GetMethod( - nameof(PropertyBuilder.HasConversion), [typeof(Type), typeof(ValueComparer)]), + nameof(PropertyBuilder.HasConversion), [typeof(Type), typeof(ValueComparer)])!, typeof(PropertyBuilder<>).GetMethod( nameof(PropertyBuilder.HasConversion), - [typeof(Type), typeof(ValueComparer), typeof(ValueComparer)]), + [typeof(Type), typeof(ValueComparer), typeof(ValueComparer)])!, typeof(PropertyBuilder<>).GetMethod( - nameof(PropertyBuilder.HasConversion), [typeof(ValueConverter), typeof(ValueComparer)]), + nameof(PropertyBuilder.HasConversion), [typeof(ValueConverter), typeof(ValueComparer)])!, typeof(PropertyBuilder<>).GetMethod( nameof(PropertyBuilder.HasConversion), - [typeof(ValueConverter), typeof(ValueComparer), typeof(ValueComparer)]), + [typeof(ValueConverter), typeof(ValueComparer), typeof(ValueComparer)])!, typeof(PropertyBuilder<>).GetMethod( - nameof(PropertyBuilder.HasConversion), [typeof(Type), typeof(Type)]), + nameof(PropertyBuilder.HasConversion), [typeof(Type), typeof(Type)])!, typeof(PropertyBuilder<>).GetMethod( - nameof(PropertyBuilder.HasConversion), [typeof(Type), typeof(Type), typeof(Type)]), + nameof(PropertyBuilder.HasConversion), [typeof(Type), typeof(Type), typeof(Type)])!, GetMethod( typeof(PropertyBuilder<>), nameof(PropertyBuilder.HasConversion), genericParameterCount: 1, (typeGenerics, methodGenerics) => (typeGenerics.Length < 1 || methodGenerics.Length < 1) @@ -520,45 +520,45 @@ public class RelationalApiConsistencyFixture : ApiConsistencyFixtureBase public override HashSet AsyncMethodExceptions { get; } = [ - typeof(RelationalDatabaseFacadeExtensions).GetMethod(nameof(RelationalDatabaseFacadeExtensions.CloseConnectionAsync)), - typeof(IRelationalConnection).GetMethod(nameof(IRelationalConnection.CloseAsync)), - typeof(RelationalConnection).GetMethod(nameof(RelationalConnection.CloseAsync)), - typeof(RelationalConnection).GetMethod("CloseDbConnectionAsync", BindingFlags.NonPublic | BindingFlags.Instance), - typeof(DbConnectionInterceptor).GetMethod(nameof(DbConnectionInterceptor.ConnectionClosingAsync)), - typeof(DbConnectionInterceptor).GetMethod(nameof(DbConnectionInterceptor.ConnectionClosedAsync)), - typeof(IDbConnectionInterceptor).GetMethod(nameof(IDbConnectionInterceptor.ConnectionClosingAsync)), - typeof(IDbConnectionInterceptor).GetMethod(nameof(IDbConnectionInterceptor.ConnectionClosedAsync)), - typeof(IDbConnectionInterceptor).GetMethod(nameof(IDbConnectionInterceptor.ConnectionDisposingAsync)), - typeof(IDbConnectionInterceptor).GetMethod(nameof(IDbConnectionInterceptor.ConnectionDisposedAsync)), + typeof(RelationalDatabaseFacadeExtensions).GetMethod(nameof(RelationalDatabaseFacadeExtensions.CloseConnectionAsync))!, + typeof(IRelationalConnection).GetMethod(nameof(IRelationalConnection.CloseAsync))!, + typeof(RelationalConnection).GetMethod(nameof(RelationalConnection.CloseAsync))!, + typeof(RelationalConnection).GetMethod("CloseDbConnectionAsync", BindingFlags.NonPublic | BindingFlags.Instance)!, + typeof(DbConnectionInterceptor).GetMethod(nameof(DbConnectionInterceptor.ConnectionClosingAsync))!, + typeof(DbConnectionInterceptor).GetMethod(nameof(DbConnectionInterceptor.ConnectionClosedAsync))!, + typeof(IDbConnectionInterceptor).GetMethod(nameof(IDbConnectionInterceptor.ConnectionClosingAsync))!, + typeof(IDbConnectionInterceptor).GetMethod(nameof(IDbConnectionInterceptor.ConnectionClosedAsync))!, + typeof(IDbConnectionInterceptor).GetMethod(nameof(IDbConnectionInterceptor.ConnectionDisposingAsync))!, + typeof(IDbConnectionInterceptor).GetMethod(nameof(IDbConnectionInterceptor.ConnectionDisposedAsync))!, typeof(IRelationalConnectionDiagnosticsLogger).GetMethod( - nameof(IRelationalConnectionDiagnosticsLogger.ConnectionClosingAsync)), + nameof(IRelationalConnectionDiagnosticsLogger.ConnectionClosingAsync))!, typeof(IRelationalConnectionDiagnosticsLogger).GetMethod( - nameof(IRelationalConnectionDiagnosticsLogger.ConnectionClosedAsync)), + nameof(IRelationalConnectionDiagnosticsLogger.ConnectionClosedAsync))!, typeof(IRelationalConnectionDiagnosticsLogger).GetMethod( - nameof(IRelationalConnectionDiagnosticsLogger.ConnectionDisposingAsync)), + nameof(IRelationalConnectionDiagnosticsLogger.ConnectionDisposingAsync))!, typeof(IRelationalConnectionDiagnosticsLogger).GetMethod( - nameof(IRelationalConnectionDiagnosticsLogger.ConnectionDisposedAsync)), + nameof(IRelationalConnectionDiagnosticsLogger.ConnectionDisposedAsync))!, typeof(RelationalConnectionDiagnosticsLogger).GetMethod( - nameof(IRelationalConnectionDiagnosticsLogger.ConnectionClosingAsync)), + nameof(IRelationalConnectionDiagnosticsLogger.ConnectionClosingAsync))!, typeof(RelationalConnectionDiagnosticsLogger).GetMethod( - nameof(IRelationalConnectionDiagnosticsLogger.ConnectionClosedAsync)), + nameof(IRelationalConnectionDiagnosticsLogger.ConnectionClosedAsync))!, typeof(RelationalConnectionDiagnosticsLogger).GetMethod( - nameof(IRelationalConnectionDiagnosticsLogger.ConnectionDisposingAsync)), + nameof(IRelationalConnectionDiagnosticsLogger.ConnectionDisposingAsync))!, typeof(RelationalConnectionDiagnosticsLogger).GetMethod( - nameof(IRelationalConnectionDiagnosticsLogger.ConnectionDisposedAsync)), + nameof(IRelationalConnectionDiagnosticsLogger.ConnectionDisposedAsync))!, // internal methods made public for AOT typeof(ShaperProcessingExpressionVisitor).GetMethod( - nameof(ShaperProcessingExpressionVisitor.PopulateSplitIncludeCollectionAsync)), - typeof(ShaperProcessingExpressionVisitor).GetMethod(nameof(ShaperProcessingExpressionVisitor.PopulateSplitCollectionAsync)), - typeof(ShaperProcessingExpressionVisitor).GetMethod(nameof(ShaperProcessingExpressionVisitor.TaskAwaiter)), - typeof(RelationalShapedQueryCompilingExpressionVisitor).GetMethod(nameof(NonQueryResultAsync)), + nameof(ShaperProcessingExpressionVisitor.PopulateSplitIncludeCollectionAsync))!, + typeof(ShaperProcessingExpressionVisitor).GetMethod(nameof(ShaperProcessingExpressionVisitor.PopulateSplitCollectionAsync))!, + typeof(ShaperProcessingExpressionVisitor).GetMethod(nameof(ShaperProcessingExpressionVisitor.TaskAwaiter))!, + typeof(RelationalShapedQueryCompilingExpressionVisitor).GetMethod(nameof(NonQueryResultAsync))!, ]; public override HashSet MetadataMethodExceptions { get; } = [ - typeof(IMutableStoredProcedure).GetMethod(nameof(IMutableStoredProcedure.AddParameter)), - typeof(IMutableStoredProcedure).GetMethod(nameof(IMutableStoredProcedure.AddResultColumn)) + typeof(IMutableStoredProcedure).GetMethod(nameof(IMutableStoredProcedure.AddParameter))!, + typeof(IMutableStoredProcedure).GetMethod(nameof(IMutableStoredProcedure.AddResultColumn))! ]; public List> RelationalMetadataMethods { get; } = []; @@ -616,7 +616,7 @@ protected override void Initialize() typeof(RelationalComplexTypePrimitiveCollectionBuilderExtensions), typeof(RelationalComplexTypePropertyBuilderExtensions)); NonCancellableAsyncMethods.Add( - typeof(DbConnectionInterceptor).GetMethod(nameof(DbConnectionInterceptor.ConnectionDisposedAsync))); + typeof(DbConnectionInterceptor).GetMethod(nameof(DbConnectionInterceptor.ConnectionDisposedAsync))!); base.Initialize(); } diff --git a/test/EFCore.Relational.Tests/RelationalConnectionTest.cs b/test/EFCore.Relational.Tests/RelationalConnectionTest.cs index 547396a894b..d4ca81eb238 100644 --- a/test/EFCore.Relational.Tests/RelationalConnectionTest.cs +++ b/test/EFCore.Relational.Tests/RelationalConnectionTest.cs @@ -67,7 +67,7 @@ public void Throws_with_add_when_no_provider_use_Database() using var serviceScope = appServiceProvider .GetRequiredService() .CreateScope(); - var context = serviceScope.ServiceProvider.GetService(); + var context = serviceScope.ServiceProvider.GetService()!; Assert.Equal( CoreStrings.NoProviderConfigured, @@ -93,7 +93,7 @@ public void Throws_with_add_when_no_EF_services_because_parameterless_constructo using var serviceScope = appServiceProvider .GetRequiredService() .CreateScope(); - var context = serviceScope.ServiceProvider.GetService(); + var context = serviceScope.ServiceProvider.GetService()!; Assert.Equal( CoreStrings.NoProviderConfigured, @@ -772,7 +772,7 @@ public void Can_use_existing_transaction() using (connection.UseTransaction(dbTransaction)) { - Assert.Equal(dbTransaction, connection.CurrentTransaction.GetDbTransaction()); + Assert.Equal(dbTransaction, connection.CurrentTransaction!.GetDbTransaction()); } Assert.Null(connection.CurrentTransaction); @@ -793,7 +793,7 @@ public void Can_use_existing_transaction_identifier() using (var transaction = connection.UseTransaction(dbTransaction, transactionId)) { - Assert.Equal(dbTransaction, connection.CurrentTransaction.GetDbTransaction()); + Assert.Equal(dbTransaction, connection.CurrentTransaction!.GetDbTransaction()); Assert.Equal(transactionId, transaction.TransactionId); } @@ -941,7 +941,7 @@ public void Throws_if_multiple_relational_stores_configured() private class AnotherFakeRelationalOptionsExtension : RelationalOptionsExtension { - private DbContextOptionsExtensionInfo _info; + private DbContextOptionsExtensionInfo? _info; public AnotherFakeRelationalOptionsExtension() { @@ -1171,7 +1171,7 @@ public void Validate(IDbContextOptions options) public bool DetailedErrorsEnabled { get; } = detailedErrorsEnabled; public WarningsConfiguration WarningsConfiguration - => null; + => null!; public virtual bool ShouldWarnForStringEnumValueInJson(Type enumType) => true; diff --git a/test/EFCore.Relational.Tests/Storage/NamedConnectionStringResolverTest.cs b/test/EFCore.Relational.Tests/Storage/NamedConnectionStringResolverTest.cs index f5acd031d10..3cdc16ff5de 100644 --- a/test/EFCore.Relational.Tests/Storage/NamedConnectionStringResolverTest.cs +++ b/test/EFCore.Relational.Tests/Storage/NamedConnectionStringResolverTest.cs @@ -45,7 +45,7 @@ public void Returns_resolved_string_if_IConfiguration_contains_key() new FakeOptions( new ConfigurationBuilder() .AddInMemoryCollection( - new Dictionary + new Dictionary { { "MyConnectionString", "Conn1" }, { "ConnectionStrings:DefaultConnection", "Conn2" }, @@ -68,7 +68,7 @@ public void Returns_given_string_named_connection_string_doesnt_match_pattern() new FakeOptions( new ConfigurationBuilder() .AddInMemoryCollection( - new Dictionary { { "Nope", "NoThanks" } }) + new Dictionary { { "Nope", "NoThanks" } }) .Build())); Assert.Equal("name=Fox;DataSource=Jimony", resolver.ResolveConnectionString("name=Fox;DataSource=Jimony")); @@ -78,9 +78,9 @@ public void Returns_given_string_named_connection_string_doesnt_match_pattern() private class FakeOptions : IDbContextOptions { - private readonly IServiceProvider _serviceProvider; + private readonly IServiceProvider? _serviceProvider; - public FakeOptions(IConfiguration configuration, bool useServiceProvider = true) + public FakeOptions(IConfiguration? configuration, bool useServiceProvider = true) { if (useServiceProvider) { @@ -96,7 +96,7 @@ public FakeOptions(IConfiguration configuration, bool useServiceProvider = true) } public IEnumerable Extensions - => null; + => null!; public TExtension FindExtension() where TExtension : class, IDbContextOptionsExtension diff --git a/test/EFCore.Relational.Tests/Storage/RelationalCommandTest.cs b/test/EFCore.Relational.Tests/Storage/RelationalCommandTest.cs index 91b89a149b8..5de6e9a1f46 100644 --- a/test/EFCore.Relational.Tests/Storage/RelationalCommandTest.cs +++ b/test/EFCore.Relational.Tests/Storage/RelationalCommandTest.cs @@ -7,12 +7,12 @@ using Microsoft.EntityFrameworkCore.TestUtilities.FakeProvider; using CommandAction = System.Action< Microsoft.EntityFrameworkCore.Storage.IRelationalConnection, - Microsoft.EntityFrameworkCore.Storage.IRelationalCommand, System.Collections.Generic.IReadOnlyDictionary, - Microsoft.EntityFrameworkCore.Diagnostics.IRelationalCommandDiagnosticsLogger>; + Microsoft.EntityFrameworkCore.Storage.IRelationalCommand, System.Collections.Generic.IReadOnlyDictionary?, + Microsoft.EntityFrameworkCore.Diagnostics.IRelationalCommandDiagnosticsLogger?>; using CommandFunc = System.Func< Microsoft.EntityFrameworkCore.Storage.IRelationalConnection, - Microsoft.EntityFrameworkCore.Storage.IRelationalCommand, System.Collections.Generic.IReadOnlyDictionary, - Microsoft.EntityFrameworkCore.Diagnostics.IRelationalCommandDiagnosticsLogger, + Microsoft.EntityFrameworkCore.Storage.IRelationalCommand, System.Collections.Generic.IReadOnlyDictionary?, + Microsoft.EntityFrameworkCore.Diagnostics.IRelationalCommandDiagnosticsLogger?, System.Threading.Tasks.Task>; // ReSharper disable InconsistentNaming @@ -187,7 +187,7 @@ public void Can_ExecuteScalar() var result = (string)relationalCommand.ExecuteScalar( new RelationalCommandParameterObject( - new FakeRelationalConnection(options), null, null, null, null)); + new FakeRelationalConnection(options), null, null, null, null))!; Assert.Equal("ExecuteScalar Result", result); @@ -216,7 +216,7 @@ public async Task Can_ExecuteScalarAsync() { executeScalarCount++; disposeCount = c.DisposeCount; - return Task.FromResult("ExecuteScalar Result"); + return Task.FromResult("ExecuteScalar Result"); })); var optionsExtension = new FakeRelationalOptionsExtension().WithConnection(fakeDbConnection); @@ -225,9 +225,9 @@ public async Task Can_ExecuteScalarAsync() var relationalCommand = CreateRelationalCommand(); - var result = (string)await relationalCommand.ExecuteScalarAsync( + var result = (string)(await relationalCommand.ExecuteScalarAsync( new RelationalCommandParameterObject( - new FakeRelationalConnection(options), null, null, null, null)); + new FakeRelationalConnection(options), null, null, null, null)))!; Assert.Equal("ExecuteScalar Result", result); @@ -523,7 +523,7 @@ public async Task Throws_when_parameters_are_configured_and_value_is_missing( new TypeMappedRelationalParameter("ThirdInvariant", "ThirdParameter", RelationalTypeMapping.NullMapping, null) ]); - var parameterValues = new Dictionary { { "FirstInvariant", 17 }, { "SecondInvariant", 18L } }; + var parameterValues = new Dictionary { { "FirstInvariant", 17 }, { "SecondInvariant", 18L } }; if (async) { @@ -559,7 +559,7 @@ public async Task Configures_DbCommand_with_type_mapped_parameters( new TypeMappedRelationalParameter("ThirdInvariant", "ThirdParameter", RelationalTypeMapping.NullMapping, null) ]); - var parameterValues = new Dictionary + var parameterValues = new Dictionary { { "FirstInvariant", 17 }, { "SecondInvariant", 18L }, @@ -626,7 +626,7 @@ public async Task Configures_DbCommand_with_composite_parameters( ]) ]); - var parameterValues = new Dictionary { { "CompositeInvariant", new object[] { 17, 18L, null } } }; + var parameterValues = new Dictionary { { "CompositeInvariant", new object?[] { 17, 18L, null } } }; if (async) { @@ -688,7 +688,7 @@ public async Task Throws_when_composite_parameters_are_configured_and_value_is_m ]) ]); - var parameterValues = new Dictionary { { "CompositeInvariant", new object[] { 17, 18L } } }; + var parameterValues = new Dictionary { { "CompositeInvariant", new object?[] { 17, 18L } } }; if (async) { @@ -726,7 +726,7 @@ public async Task Throws_when_composite_parameters_are_configured_and_value_is_n ]) ]); - var parameterValues = new Dictionary { { "CompositeInvariant", 17 } }; + var parameterValues = new Dictionary { { "CompositeInvariant", 17 } }; if (async) { @@ -842,7 +842,7 @@ public override void Initialize( DbCommand command, DbDataReader reader, Guid commandId, - IRelationalCommandDiagnosticsLogger logger) + IRelationalCommandDiagnosticsLogger? logger) => throw new InvalidOperationException("Bang!"); } } @@ -964,7 +964,7 @@ public async Task Logs_commands_without_parameter_values( "FirstInvariant", "FirstParameter", new IntTypeMapping("int"), false) ]); - var parameterValues = new Dictionary { { "FirstInvariant", 17 } }; + var parameterValues = new Dictionary { { "FirstInvariant", 17 } }; if (async) { @@ -1022,7 +1022,7 @@ public async Task Logs_commands_parameter_values( "FirstInvariant", "FirstParameter", new IntTypeMapping("int"), false) ]); - var parameterValues = new Dictionary { { "FirstInvariant", 17 } }; + var parameterValues = new Dictionary { { "FirstInvariant", 17 } }; if (async) { @@ -1080,7 +1080,7 @@ public async Task Reports_command_diagnostic( "FirstInvariant", "FirstParameter", new IntTypeMapping("int"), false) ]); - var parameterValues = new Dictionary { { "FirstInvariant", 17 } }; + var parameterValues = new Dictionary { { "FirstInvariant", 17 } }; if (async) { @@ -1152,7 +1152,7 @@ public async Task Reports_command_diagnostic_on_exception( "FirstInvariant", "FirstParameter", new IntTypeMapping("int"), false) ]); - var parameterValues = new Dictionary { { "FirstInvariant", 17 } }; + var parameterValues = new Dictionary { { "FirstInvariant", 17 } }; if (async) { @@ -1228,7 +1228,7 @@ public async Task Reports_command_diagnostic_on_cancellation( "FirstInvariant", "FirstParameter", new IntTypeMapping("int"), false) ]); - var parameterValues = new Dictionary { { "FirstInvariant", 17 } }; + var parameterValues = new Dictionary { { "FirstInvariant", 17 } }; if (async) { @@ -1263,11 +1263,11 @@ await Assert.ThrowsAsync(async () private const string ConnectionString = "Fake Connection String"; - private static FakeRelationalConnection CreateConnection(IDbContextOptions options = null) + private static FakeRelationalConnection CreateConnection(IDbContextOptions? options = null) => new(options ?? CreateOptions()); private static IDbContextOptions CreateOptions( - RelationalOptionsExtension optionsExtension = null) + RelationalOptionsExtension? optionsExtension = null) { var optionsBuilder = new DbContextOptionsBuilder(); @@ -1295,7 +1295,7 @@ public void Validate(IDbContextOptions options) public bool DetailedErrorsEnabled { get; } = detailedErrorsEnabled; public WarningsConfiguration WarningsConfiguration - => null; + => null!; public virtual bool ShouldWarnForStringEnumValueInJson(Type enumType) => true; @@ -1304,7 +1304,7 @@ public virtual bool ShouldWarnForStringEnumValueInJson(Type enumType) private IRelationalCommand CreateRelationalCommand( string commandText = "Command Text", string logCommandText = "Log Command Text", - IReadOnlyList parameters = null) + IReadOnlyList? parameters = null) => new RelationalCommand( new RelationalCommandBuilderDependencies( new TestRelationalTypeMappingSource( diff --git a/test/EFCore.Relational.Tests/Storage/RelationalDataReaderTest.cs b/test/EFCore.Relational.Tests/Storage/RelationalDataReaderTest.cs index 6b6a6598470..020a514c39c 100644 --- a/test/EFCore.Relational.Tests/Storage/RelationalDataReaderTest.cs +++ b/test/EFCore.Relational.Tests/Storage/RelationalDataReaderTest.cs @@ -20,7 +20,7 @@ public async Task Does_not_hold_reference_to_DbDataReader_after_dispose(bool asy var reader = relationalCommand.ExecuteReader( new RelationalCommandParameterObject( fakeConnection, - new Dictionary(), + new Dictionary(), readerColumns: null, context: null, logger: null)); @@ -41,11 +41,11 @@ public async Task Does_not_hold_reference_to_DbDataReader_after_dispose(bool asy private const string ConnectionString = "Fake Connection String"; - private static FakeRelationalConnection CreateConnection(IDbContextOptions options = null) + private static FakeRelationalConnection CreateConnection(IDbContextOptions? options = null) => new(options ?? CreateOptions()); private static IDbContextOptions CreateOptions( - RelationalOptionsExtension optionsExtension = null) + RelationalOptionsExtension? optionsExtension = null) { var optionsBuilder = new DbContextOptionsBuilder(); @@ -60,7 +60,7 @@ private static IDbContextOptions CreateOptions( private IRelationalCommand CreateRelationalCommand( string commandText = "Command Text", string logCommandText = "Log Command Text", - IReadOnlyList parameters = null) + IReadOnlyList? parameters = null) => new RelationalCommand( new RelationalCommandBuilderDependencies( new TestRelationalTypeMappingSource( diff --git a/test/EFCore.Relational.Tests/Storage/RelationalGeometryTypeMappingTest.cs b/test/EFCore.Relational.Tests/Storage/RelationalGeometryTypeMappingTest.cs index a858cc4fe1e..1fd61d2eb31 100644 --- a/test/EFCore.Relational.Tests/Storage/RelationalGeometryTypeMappingTest.cs +++ b/test/EFCore.Relational.Tests/Storage/RelationalGeometryTypeMappingTest.cs @@ -32,7 +32,7 @@ private FakeRelationalGeometryTypeMapping(RelationalTypeMappingParameters parame protected override RelationalTypeMapping Clone(RelationalTypeMappingParameters parameters) => new FakeRelationalGeometryTypeMapping(parameters); - protected override Type WktReaderType { get; } + protected override Type WktReaderType { get; } = null!; protected override string AsText(object value) => throw new NotImplementedException(); diff --git a/test/EFCore.Relational.Tests/Storage/RelationalParameterBuilderTest.cs b/test/EFCore.Relational.Tests/Storage/RelationalParameterBuilderTest.cs index cdf2f5805e3..c9eeafd94eb 100644 --- a/test/EFCore.Relational.Tests/Storage/RelationalParameterBuilderTest.cs +++ b/test/EFCore.Relational.Tests/Storage/RelationalParameterBuilderTest.cs @@ -26,7 +26,7 @@ public void Can_add_type_mapped_parameter_by_type(bool nullable) parameterBuilder.AddParameter( "InvariantName", "Name", - typeMapping, + typeMapping!, nullable); Assert.Equal(1, parameterBuilder.Parameters.Count); @@ -53,7 +53,7 @@ public void Can_add_type_mapped_parameter_by_property(bool nullable) var model = modelBuilder.FinalizeModel(designTime: false, skipValidation: true); - var property = model.GetEntityTypes().Single().FindProperty("MyProp"); + var property = model.GetEntityTypes().Single().FindProperty("MyProp")!; var parameterBuilder = new RelationalCommandBuilder( new RelationalCommandBuilderDependencies(typeMapper, new ExceptionDetector(), new LoggingOptions())); @@ -135,5 +135,5 @@ public void Does_not_add_empty_composite_parameter() public static RelationalTypeMapping GetMapping( IRelationalTypeMappingSource typeMappingSource, IProperty property) - => typeMappingSource.FindMapping(property); + => typeMappingSource.FindMapping(property)!; } diff --git a/test/EFCore.Relational.Tests/Storage/RelationalTypeMappingSourceTest.cs b/test/EFCore.Relational.Tests/Storage/RelationalTypeMappingSourceTest.cs index c791a22df0c..01e25e1f8cd 100644 --- a/test/EFCore.Relational.Tests/Storage/RelationalTypeMappingSourceTest.cs +++ b/test/EFCore.Relational.Tests/Storage/RelationalTypeMappingSourceTest.cs @@ -107,11 +107,11 @@ public void Key_with_store_type_is_picked_up_by_FK() Assert.Equal( "money", - GetMapping(mapper, model.FindEntityType(typeof(MyType)).FindProperty("Id")).StoreType); + GetMapping(mapper, model.FindEntityType(typeof(MyType))!.FindProperty("Id")!).StoreType); Assert.Equal( "money", - GetMapping(mapper, model.FindEntityType(typeof(MyRelatedType1)).FindProperty("Relationship1Id")).StoreType); + GetMapping(mapper, model.FindEntityType(typeof(MyRelatedType1))!.FindProperty("Relationship1Id")!).StoreType); } [Fact] @@ -122,7 +122,7 @@ public void Does_default_type_mapping_from_decimal() Assert.Equal( "default_decimal_mapping", - GetMapping(mapper, model.FindEntityType(typeof(MyPrecisionType)).FindProperty("Id")).StoreType); + GetMapping(mapper, model.FindEntityType(typeof(MyPrecisionType))!.FindProperty("Id")!).StoreType); } [Fact] @@ -133,7 +133,7 @@ public void Does_type_mapping_from_decimal_with_precision_only() Assert.Equal( "decimal_mapping(16)", - GetMapping(mapper, model.FindEntityType(typeof(MyPrecisionType)).FindProperty("PrecisionOnly")).StoreType); + GetMapping(mapper, model.FindEntityType(typeof(MyPrecisionType))!.FindProperty("PrecisionOnly")!).StoreType); } [Fact] @@ -144,7 +144,7 @@ public void Does_type_mapping_from_decimal_with_precision_and_scale() Assert.Equal( "decimal_mapping(18,7)", - GetMapping(mapper, model.FindEntityType(typeof(MyPrecisionType)).FindProperty("PrecisionAndScale")).StoreType); + GetMapping(mapper, model.FindEntityType(typeof(MyPrecisionType))!.FindProperty("PrecisionAndScale")!).StoreType); } [Fact] @@ -243,10 +243,10 @@ protected override IRelationalTypeMappingSource CreateRelationalTypeMappingSourc TestServiceFactory.Instance.Create()); public RelationalTypeMapping GetMapping(Type type) - => CreateRelationalTypeMappingSource(CreateModel()).FindMapping(type); + => CreateRelationalTypeMappingSource(CreateModel()).FindMapping(type)!; public RelationalTypeMapping GetMapping(IProperty property) - => CreateRelationalTypeMappingSource(CreateModel()).FindMapping(property); + => CreateRelationalTypeMappingSource(CreateModel()).FindMapping(property)!; [Fact] public void String_key_with_max_fixed_length_is_picked_up_by_FK() @@ -256,11 +256,11 @@ public void String_key_with_max_fixed_length_is_picked_up_by_FK() Assert.Equal( "just_string_fixed(200)", - GetMapping(mapper, model.FindEntityType(typeof(MyRelatedType1)).FindProperty("Id")).StoreType); + GetMapping(mapper, model.FindEntityType(typeof(MyRelatedType1))!.FindProperty("Id")!).StoreType); Assert.Equal( "just_string_fixed(200)", - GetMapping(mapper, model.FindEntityType(typeof(MyRelatedType2)).FindProperty("Relationship1Id")).StoreType); + GetMapping(mapper, model.FindEntityType(typeof(MyRelatedType2))!.FindProperty("Relationship1Id")!).StoreType); } [Fact] @@ -271,11 +271,11 @@ public void Binary_key_with_max_fixed_length_is_picked_up_by_FK() Assert.Equal( "just_binary_fixed(100)", - GetMapping(mapper, model.FindEntityType(typeof(MyRelatedType2)).FindProperty("Id")).StoreType); + GetMapping(mapper, model.FindEntityType(typeof(MyRelatedType2))!.FindProperty("Id")!).StoreType); Assert.Equal( "just_binary_fixed(100)", - GetMapping(mapper, model.FindEntityType(typeof(MyRelatedType3)).FindProperty("Relationship1Id")).StoreType); + GetMapping(mapper, model.FindEntityType(typeof(MyRelatedType3))!.FindProperty("Relationship1Id")!).StoreType); } [Fact] @@ -286,11 +286,11 @@ public void String_key_with_unicode_is_picked_up_by_FK() Assert.Equal( "ansi_string(900)", - GetMapping(mapper, model.FindEntityType(typeof(MyRelatedType3)).FindProperty("Id")).StoreType); + GetMapping(mapper, model.FindEntityType(typeof(MyRelatedType3))!.FindProperty("Id")!).StoreType); Assert.Equal( "ansi_string(900)", - GetMapping(mapper, model.FindEntityType(typeof(MyRelatedType4)).FindProperty("Relationship1Id")).StoreType); + GetMapping(mapper, model.FindEntityType(typeof(MyRelatedType4))!.FindProperty("Relationship1Id")!).StoreType); } [Fact] @@ -301,11 +301,11 @@ public void Key_store_type_is_preferred_if_specified() Assert.Equal( "money", - GetMapping(mapper, model.FindEntityType(typeof(MyType)).FindProperty("Id")).StoreType); + GetMapping(mapper, model.FindEntityType(typeof(MyType))!.FindProperty("Id")!).StoreType); Assert.Equal( "decimal_mapping(6,1)", - GetMapping(mapper, model.FindEntityType(typeof(MyRelatedType1)).FindProperty("Relationship2Id")).StoreType); + GetMapping(mapper, model.FindEntityType(typeof(MyRelatedType1))!.FindProperty("Relationship2Id")!).StoreType); } [Fact] @@ -316,11 +316,11 @@ public void String_FK_max_length_is_preferred_if_specified() Assert.Equal( "just_string_fixed(200)", - GetMapping(mapper, model.FindEntityType(typeof(MyRelatedType1)).FindProperty("Id")).StoreType); + GetMapping(mapper, model.FindEntityType(typeof(MyRelatedType1))!.FindProperty("Id")!).StoreType); Assert.Equal( "just_string_fixed(787)", - GetMapping(mapper, model.FindEntityType(typeof(MyRelatedType2)).FindProperty("Relationship2Id")).StoreType); + GetMapping(mapper, model.FindEntityType(typeof(MyRelatedType2))!.FindProperty("Relationship2Id")!).StoreType); } [Fact] @@ -331,11 +331,11 @@ public void Binary_FK_max_length_is_preferred_if_specified() Assert.Equal( "just_binary_fixed(100)", - GetMapping(mapper, model.FindEntityType(typeof(MyRelatedType2)).FindProperty("Id")).StoreType); + GetMapping(mapper, model.FindEntityType(typeof(MyRelatedType2))!.FindProperty("Id")!).StoreType); Assert.Equal( "just_binary_fixed(767)", - GetMapping(mapper, model.FindEntityType(typeof(MyRelatedType3)).FindProperty("Relationship2Id")).StoreType); + GetMapping(mapper, model.FindEntityType(typeof(MyRelatedType3))!.FindProperty("Relationship2Id")!).StoreType); } [Fact] @@ -346,18 +346,18 @@ public void String_FK_unicode_is_preferred_if_specified() Assert.Equal( "ansi_string(900)", - GetMapping(mapper, model.FindEntityType(typeof(MyRelatedType3)).FindProperty("Id")).StoreType); + GetMapping(mapper, model.FindEntityType(typeof(MyRelatedType3))!.FindProperty("Id")!).StoreType); Assert.Equal( "just_string(450)", - GetMapping(mapper, model.FindEntityType(typeof(MyRelatedType4)).FindProperty("Relationship2Id")).StoreType); + GetMapping(mapper, model.FindEntityType(typeof(MyRelatedType4))!.FindProperty("Relationship2Id")!).StoreType); } public static RelationalTypeMapping GetMapping( IRelationalTypeMappingSource typeMappingSource, IProperty property) - => typeMappingSource.FindMapping(property); + => typeMappingSource.FindMapping(property)!; - protected override ModelBuilder CreateModelBuilder(Action configureConventions = null) + protected override ModelBuilder CreateModelBuilder(Action? configureConventions = null) => FakeRelationalTestHelpers.Instance.CreateConventionBuilder(configureConventions: configureConventions); } diff --git a/test/EFCore.Relational.Tests/Storage/RelationalTypeMappingSourceTestBase.cs b/test/EFCore.Relational.Tests/Storage/RelationalTypeMappingSourceTestBase.cs index bfba785ca57..9562b589ab4 100644 --- a/test/EFCore.Relational.Tests/Storage/RelationalTypeMappingSourceTestBase.cs +++ b/test/EFCore.Relational.Tests/Storage/RelationalTypeMappingSourceTestBase.cs @@ -22,7 +22,7 @@ protected IMutableEntityType CreateEntityType() builder.Entity(); builder.Entity(); - return builder.Model.FindEntityType(typeof(TEntity)); + return builder.Model.FindEntityType(typeof(TEntity))!; } protected IModel CreateModel() @@ -34,10 +34,10 @@ protected RelationalTypeMapping GetTypeMapping( int? maxLength = null, int? precision = null, int? scale = null, - Type providerType = null, + Type? providerType = null, bool? unicode = null, bool? fixedLength = null, - string storeTypeName = null, + string? storeTypeName = null, bool useConfiguration = false) { if (useConfiguration) @@ -134,11 +134,11 @@ protected RelationalTypeMapping GetTypeMapping( } var model = modelBuilder.Model.FinalizeModel(); - return CreateRelationalTypeMappingSource(model).GetMapping(model.FindEntityType(typeof(MyType)).FindProperty(property.Name)); + return CreateRelationalTypeMappingSource(model).GetMapping(model.FindEntityType(typeof(MyType))!.FindProperty(property.Name)!); } } - protected abstract ModelBuilder CreateModelBuilder(Action configureConventions = null); + protected abstract ModelBuilder CreateModelBuilder(Action? configureConventions = null); protected abstract IRelationalTypeMappingSource CreateRelationalTypeMappingSource(IModel model); protected class MyType @@ -155,59 +155,59 @@ protected class MyPrecisionType protected class MyRelatedType1 { - public string Id { get; set; } + public string Id { get; set; } = null!; public decimal Relationship1Id { get; set; } - public MyType Relationship1 { get; set; } + public MyType Relationship1 { get; set; } = null!; public decimal Relationship2Id { get; set; } - public MyType Relationship2 { get; set; } + public MyType Relationship2 { get; set; } = null!; } protected class MyRelatedType2 { - public byte[] Id { get; set; } + public byte[] Id { get; set; } = null!; - public string Relationship1Id { get; set; } - public MyRelatedType1 Relationship1 { get; set; } + public string Relationship1Id { get; set; } = null!; + public MyRelatedType1 Relationship1 { get; set; } = null!; - public string Relationship2Id { get; set; } - public MyRelatedType1 Relationship2 { get; set; } + public string Relationship2Id { get; set; } = null!; + public MyRelatedType1 Relationship2 { get; set; } = null!; } protected class MyRelatedType3 { - public string Id { get; set; } + public string Id { get; set; } = null!; - public byte[] Relationship1Id { get; set; } - public MyRelatedType2 Relationship1 { get; set; } + public byte[] Relationship1Id { get; set; } = null!; + public MyRelatedType2 Relationship1 { get; set; } = null!; - public byte[] Relationship2Id { get; set; } - public MyRelatedType2 Relationship2 { get; set; } + public byte[] Relationship2Id { get; set; } = null!; + public MyRelatedType2 Relationship2 { get; set; } = null!; } protected class MyRelatedType4 { - public string Id { get; set; } + public string Id { get; set; } = null!; - public string Relationship1Id { get; set; } - public MyRelatedType3 Relationship1 { get; set; } + public string Relationship1Id { get; set; } = null!; + public MyRelatedType3 Relationship1 { get; set; } = null!; - public string Relationship2Id { get; set; } - public MyRelatedType3 Relationship2 { get; set; } + public string Relationship2Id { get; set; } = null!; + public MyRelatedType3 Relationship2 { get; set; } = null!; } [Index(nameof(Name))] protected class MyTypeWithIndexAttribute { public int Id { get; set; } - public string Name { get; set; } + public string Name { get; set; } = null!; } [Index(nameof(Ints))] protected class MyTypeWithIndexAttributeOnCollection { public int Id { get; set; } - public IEnumerable Ints { get; set; } + public IEnumerable Ints { get; set; } = null!; } } diff --git a/test/EFCore.Relational.Tests/Storage/RelationalTypeMappingTest.cs b/test/EFCore.Relational.Tests/Storage/RelationalTypeMappingTest.cs index 6f35a15d84b..dbd55d4aea9 100644 --- a/test/EFCore.Relational.Tests/Storage/RelationalTypeMappingTest.cs +++ b/test/EFCore.Relational.Tests/Storage/RelationalTypeMappingTest.cs @@ -9,7 +9,7 @@ namespace Microsoft.EntityFrameworkCore.Storage; public abstract class RelationalTypeMappingTest { protected class FakeValueConverter() - : ValueConverter(_ => (TProvider)(object)_, _ => (TModel)(object)_) + : ValueConverter(_ => (TProvider)(object)_!, _ => (TModel)(object)_!) { public override Type ModelClrType { get; } = typeof(TModel); public override Type ProviderClrType { get; } = typeof(TProvider); @@ -22,15 +22,15 @@ protected class FakeValueComparer() : ValueComparer(false) public static ValueConverter CreateConverter(Type modelType) => (ValueConverter)Activator.CreateInstance( - typeof(FakeValueConverter<,>).MakeGenericType(modelType, typeof(object))); + typeof(FakeValueConverter<,>).MakeGenericType(modelType, typeof(object)))!; public static ValueConverter CreateConverter(Type modelType, Type providerType) => (ValueConverter)Activator.CreateInstance( - typeof(FakeValueConverter<,>).MakeGenericType(modelType, providerType)); + typeof(FakeValueConverter<,>).MakeGenericType(modelType, providerType))!; public static ValueComparer CreateComparer(Type type) => (ValueComparer)Activator.CreateInstance( - typeof(FakeValueComparer<>).MakeGenericType(type)); + typeof(FakeValueComparer<>).MakeGenericType(type))!; [Theory, InlineData(typeof(BoolTypeMapping), typeof(bool)), InlineData(typeof(ByteTypeMapping), typeof(byte)), InlineData(typeof(CharTypeMapping), typeof(char)), InlineData(typeof(DateTimeOffsetTypeMapping), typeof(DateTimeOffset)), @@ -49,7 +49,7 @@ public virtual void Create_and_clone_with_converter(Type mappingType, Type type) null, [FakeTypeMapping.CreateParameters(type)], null, - null); + null)!; AssertClone(type, mapping); } @@ -110,7 +110,7 @@ protected virtual void ConversionCloneTest( storeTypePostfix: StoreTypePostfix.Size) }.Concat(additionalArgs).ToArray(), null, - null); + null)!; var clone = mapping.WithStoreTypeAndSize("", 66); @@ -174,7 +174,7 @@ protected virtual void UnicodeConversionCloneTest( storeTypePostfix: StoreTypePostfix.Size) }.Concat(additionalArgs).ToArray(), null, - null); + null)!; var clone = mapping.WithStoreTypeAndSize("", 66); @@ -345,7 +345,7 @@ public void Can_create_string_parameter() protected virtual void Test_GenerateSqlLiteral_helper( RelationalTypeMapping typeMapping, - object value, + object? value, string literalValue) => Assert.Equal(literalValue, typeMapping.GenerateSqlLiteral(value)); @@ -575,14 +575,14 @@ public virtual void Primary_key_type_mapping_is_picked_up_by_FK_without_going_th { using var context = new FruityContext(ContextOptions); Assert.Same( - context.Model.FindEntityType(typeof(Banana)).FindProperty("Id").GetTypeMapping(), - context.Model.FindEntityType(typeof(Kiwi)).FindProperty("BananaId").GetTypeMapping()); + context.Model.FindEntityType(typeof(Banana))!.FindProperty("Id")!.GetTypeMapping(), + context.Model.FindEntityType(typeof(Kiwi))!.FindProperty("BananaId")!.GetTypeMapping()); } private class FruityContext(DbContextOptions options) : DbContext(options) { - public DbSet Bananas { get; set; } - public DbSet Kiwi { get; set; } + public DbSet Bananas { get; set; } = null!; + public DbSet Kiwi { get; set; } = null!; } [Fact] @@ -591,8 +591,8 @@ public virtual void Primary_key_type_mapping_can_differ_from_FK() using var context = new MismatchedFruityContext(ContextOptions); Assert.Equal( typeof(short), - context.Model.FindEntityType(typeof(Banana)).FindProperty("Id").GetTypeMapping().Converter.ProviderClrType); - Assert.Null(context.Model.FindEntityType(typeof(Kiwi)).FindProperty("Id").GetTypeMapping().Converter); + context.Model.FindEntityType(typeof(Banana))!.FindProperty("Id")!.GetTypeMapping().Converter!.ProviderClrType); + Assert.Null(context.Model.FindEntityType(typeof(Kiwi))!.FindProperty("Id")!.GetTypeMapping().Converter); } private class MismatchedFruityContext(DbContextOptions options) : FruityContext(options) @@ -611,7 +611,7 @@ private class Banana { public int Id { get; set; } - public ICollection Kiwis { get; set; } + public ICollection Kiwis { get; set; } = null!; } private class Kiwi @@ -619,7 +619,7 @@ private class Kiwi public int Id { get; set; } public int BananaId { get; set; } - public Banana Banana { get; set; } + public Banana Banana { get; set; } = null!; } protected abstract DbContextOptions ContextOptions { get; } diff --git a/test/EFCore.Relational.Tests/TestUtilities/FakeDiagnosticsLogger.cs b/test/EFCore.Relational.Tests/TestUtilities/FakeDiagnosticsLogger.cs index d742f2da35a..05645a80108 100644 --- a/test/EFCore.Relational.Tests/TestUtilities/FakeDiagnosticsLogger.cs +++ b/test/EFCore.Relational.Tests/TestUtilities/FakeDiagnosticsLogger.cs @@ -24,8 +24,8 @@ public void Log( LogLevel logLevel, EventId eventId, TState state, - Exception exception, - Func formatter) + Exception? exception, + Func formatter) { } @@ -35,10 +35,11 @@ public bool IsEnabled(LogLevel logLevel) public bool IsEnabled(EventId eventId, LogLevel logLevel) => true; - public IDisposable BeginScope(TState state) + public IDisposable? BeginScope(TState state) + where TState : notnull => null; public virtual LoggingDefinitions Definitions { get; } = new TestRelationalLoggingDefinitions(); - public IInterceptors Interceptors { get; } + public IInterceptors Interceptors { get; } = null!; } diff --git a/test/EFCore.Relational.Tests/TestUtilities/FakeProvider/FakeCommandExecutor.cs b/test/EFCore.Relational.Tests/TestUtilities/FakeProvider/FakeCommandExecutor.cs index f7ed5444156..3a9aca42ea3 100644 --- a/test/EFCore.Relational.Tests/TestUtilities/FakeProvider/FakeCommandExecutor.cs +++ b/test/EFCore.Relational.Tests/TestUtilities/FakeProvider/FakeCommandExecutor.cs @@ -6,17 +6,17 @@ namespace Microsoft.EntityFrameworkCore.TestUtilities.FakeProvider; public class FakeCommandExecutor( - Func executeNonQuery = null, - Func executeScalar = null, - Func executeReader = null, - Func> executeNonQueryAsync = null, - Func> executeScalarAsync = null, - Func> executeReaderAsync = null) + Func? executeNonQuery = null, + Func? executeScalar = null, + Func? executeReader = null, + Func>? executeNonQueryAsync = null, + Func>? executeScalarAsync = null, + Func>? executeReaderAsync = null) { private readonly Func _executeNonQuery = executeNonQuery ?? (c => -1); - private readonly Func _executeScalar = executeScalar + private readonly Func _executeScalar = executeScalar ?? (c => null); private readonly Func _executeReader = executeReader @@ -25,8 +25,8 @@ public class FakeCommandExecutor( private readonly Func> _executeNonQueryAsync = executeNonQueryAsync ?? ((c, ct) => Task.FromResult(-1)); - private readonly Func> _executeScalarAsync = executeScalarAsync - ?? ((c, ct) => Task.FromResult(null)); + private readonly Func> _executeScalarAsync = executeScalarAsync + ?? ((c, ct) => Task.FromResult(null)); private readonly Func> _executeReaderAsync = executeReaderAsync ?? ((c, ct, b) => Task.FromResult(new FakeDbDataReader())); @@ -34,7 +34,7 @@ public class FakeCommandExecutor( public virtual int ExecuteNonQuery(FakeDbCommand command) => _executeNonQuery(command); - public virtual object ExecuteScalar(FakeDbCommand command) + public virtual object? ExecuteScalar(FakeDbCommand command) => _executeScalar(command); public virtual DbDataReader ExecuteReader(FakeDbCommand command, CommandBehavior behavior) @@ -43,7 +43,7 @@ public virtual DbDataReader ExecuteReader(FakeDbCommand command, CommandBehavior public Task ExecuteNonQueryAsync(FakeDbCommand command, CancellationToken cancellationToken) => _executeNonQueryAsync(command, cancellationToken); - public Task ExecuteScalarAsync(FakeDbCommand command, CancellationToken cancellationToken) + public Task ExecuteScalarAsync(FakeDbCommand command, CancellationToken cancellationToken) => _executeScalarAsync(command, cancellationToken); public Task ExecuteReaderAsync(FakeDbCommand command, CommandBehavior behavior, CancellationToken cancellationToken) diff --git a/test/EFCore.Relational.Tests/TestUtilities/FakeProvider/FakeDbCommand.cs b/test/EFCore.Relational.Tests/TestUtilities/FakeProvider/FakeDbCommand.cs index f55dc28a75f..e756cccf9a7 100644 --- a/test/EFCore.Relational.Tests/TestUtilities/FakeProvider/FakeDbCommand.cs +++ b/test/EFCore.Relational.Tests/TestUtilities/FakeProvider/FakeDbCommand.cs @@ -2,12 +2,13 @@ // The .NET Foundation licenses this file to you under the MIT license. using System.Data; +using System.Diagnostics.CodeAnalysis; namespace Microsoft.EntityFrameworkCore.TestUtilities.FakeProvider; public class FakeDbCommand : DbCommand { - private readonly FakeCommandExecutor _commandExecutor; + private readonly FakeCommandExecutor _commandExecutor = null!; public FakeDbCommand() { @@ -21,14 +22,15 @@ public FakeDbCommand( _commandExecutor = commandExecutor; } - protected override DbConnection DbConnection { get; set; } + protected override DbConnection? DbConnection { get; set; } - protected override DbTransaction DbTransaction { get; set; } + protected override DbTransaction? DbTransaction { get; set; } public override void Cancel() => throw new NotImplementedException(); - public override string CommandText { get; set; } + [AllowNull] + public override string CommandText { get; set; } = null!; public static int DefaultCommandTimeout = 30; @@ -52,7 +54,7 @@ public override int ExecuteNonQuery() return _commandExecutor.ExecuteNonQuery(this); } - public override object ExecuteScalar() + public override object? ExecuteScalar() { AssertTransaction(); @@ -73,7 +75,7 @@ public override Task ExecuteNonQueryAsync(CancellationToken cancellationTok return _commandExecutor.ExecuteNonQueryAsync(this, cancellationToken); } - public override Task ExecuteScalarAsync(CancellationToken cancellationToken) + public override Task ExecuteScalarAsync(CancellationToken cancellationToken) { AssertTransaction(); @@ -116,7 +118,7 @@ private void AssertTransaction() if (Transaction == null) { Check.DebugAssert( - ((FakeDbConnection)DbConnection).ActiveTransaction == null, + ((FakeDbConnection)DbConnection!).ActiveTransaction == null, "((FakeDbConnection)DbConnection).ActiveTransaction is null"); } else diff --git a/test/EFCore.Relational.Tests/TestUtilities/FakeProvider/FakeDbConnection.cs b/test/EFCore.Relational.Tests/TestUtilities/FakeProvider/FakeDbConnection.cs index 09552f40be2..157b2086b83 100644 --- a/test/EFCore.Relational.Tests/TestUtilities/FakeProvider/FakeDbConnection.cs +++ b/test/EFCore.Relational.Tests/TestUtilities/FakeProvider/FakeDbConnection.cs @@ -2,12 +2,13 @@ // The .NET Foundation licenses this file to you under the MIT license. using System.Data; +using System.Diagnostics.CodeAnalysis; namespace Microsoft.EntityFrameworkCore.TestUtilities.FakeProvider; public class FakeDbConnection( string connectionString, - FakeCommandExecutor commandExecutor = null, + FakeCommandExecutor? commandExecutor = null, ConnectionState state = ConnectionState.Closed) : DbConnection { private readonly FakeCommandExecutor _commandExecutor = commandExecutor ?? new FakeCommandExecutor(); @@ -25,6 +26,7 @@ public override ConnectionState State public IReadOnlyList DbCommands => _dbCommands; + [AllowNull] public override string ConnectionString { get; set; } = connectionString; public override string Database { get; } = "Fake Database"; @@ -74,7 +76,7 @@ protected override DbCommand CreateDbCommand() public IReadOnlyList DbTransactions => _dbTransactions; - public FakeDbTransaction ActiveTransaction { get; set; } + public FakeDbTransaction? ActiveTransaction { get; set; } protected override DbTransaction BeginDbTransaction(IsolationLevel isolationLevel) { diff --git a/test/EFCore.Relational.Tests/TestUtilities/FakeProvider/FakeDbDataReader.cs b/test/EFCore.Relational.Tests/TestUtilities/FakeProvider/FakeDbDataReader.cs index d60820ff43a..b03bb40195e 100644 --- a/test/EFCore.Relational.Tests/TestUtilities/FakeProvider/FakeDbDataReader.cs +++ b/test/EFCore.Relational.Tests/TestUtilities/FakeProvider/FakeDbDataReader.cs @@ -12,18 +12,18 @@ public class FakeDbDataReader : DbDataReader private readonly IList> _resultSets; private int _currentResultSet; - private object[] _currentRow; + private object[]? _currentRow; private int _rowIndex; private bool _closed; - public FakeDbDataReader(string[] columnNames = null, IList results = null) + public FakeDbDataReader(string[]? columnNames = null, IList? results = null) { _columnNames = columnNames ?? []; _results = results ?? []; _resultSets = [_results]; } - public FakeDbDataReader(string[] columnNames, IList> resultSets) + public FakeDbDataReader(string[] columnNames, IList>? resultSets) { _columnNames = columnNames ?? []; _resultSets = resultSets ?? [[]]; @@ -81,10 +81,10 @@ public override string GetName(int ordinal) => _columnNames[ordinal]; public override bool IsDBNull(int ordinal) - => _currentRow[ordinal] == DBNull.Value; + => _currentRow![ordinal] == DBNull.Value; public override object GetValue(int ordinal) - => _currentRow[ordinal]; + => _currentRow![ordinal]; public int GetInt32Count { get; private set; } @@ -92,7 +92,7 @@ public override int GetInt32(int ordinal) { GetInt32Count++; - return (int)_currentRow[ordinal]; + return (int)_currentRow![ordinal]; } public override object this[string name] @@ -114,31 +114,31 @@ public override int RecordsAffected => _resultSets.Aggregate(0, (a, r) => a + r.Count); public override bool GetBoolean(int ordinal) - => (bool)_currentRow[ordinal]; + => (bool)_currentRow![ordinal]; public override byte GetByte(int ordinal) - => (byte)_currentRow[ordinal]; + => (byte)_currentRow![ordinal]; - public override long GetBytes(int ordinal, long dataOffset, byte[] buffer, int bufferOffset, int length) + public override long GetBytes(int ordinal, long dataOffset, byte[]? buffer, int bufferOffset, int length) => throw new NotImplementedException(); public override char GetChar(int ordinal) - => (char)_currentRow[ordinal]; + => (char)_currentRow![ordinal]; - public override long GetChars(int ordinal, long dataOffset, char[] buffer, int bufferOffset, int length) + public override long GetChars(int ordinal, long dataOffset, char[]? buffer, int bufferOffset, int length) => throw new NotImplementedException(); public override string GetDataTypeName(int ordinal) => GetFieldType(ordinal).Name; public override DateTime GetDateTime(int ordinal) - => (DateTime)_currentRow[ordinal]; + => (DateTime)_currentRow![ordinal]; public override decimal GetDecimal(int ordinal) - => (decimal)_currentRow[ordinal]; + => (decimal)_currentRow![ordinal]; public override double GetDouble(int ordinal) - => (double)_currentRow[ordinal]; + => (double)_currentRow![ordinal]; public override IEnumerator GetEnumerator() => throw new NotImplementedException(); @@ -149,22 +149,22 @@ public override Type GetFieldType(int ordinal) : typeof(object); public override float GetFloat(int ordinal) - => (float)_currentRow[ordinal]; + => (float)_currentRow![ordinal]; public override Guid GetGuid(int ordinal) - => (Guid)_currentRow[ordinal]; + => (Guid)_currentRow![ordinal]; public override short GetInt16(int ordinal) - => (short)_currentRow[ordinal]; + => (short)_currentRow![ordinal]; public override long GetInt64(int ordinal) - => (long)_currentRow[ordinal]; + => (long)_currentRow![ordinal]; public override int GetOrdinal(string name) => throw new NotImplementedException(); public override string GetString(int ordinal) - => (string)_currentRow[ordinal]; + => (string)_currentRow![ordinal]; public override int GetValues(object[] values) => throw new NotImplementedException(); diff --git a/test/EFCore.Relational.Tests/TestUtilities/FakeProvider/FakeDbParameter.cs b/test/EFCore.Relational.Tests/TestUtilities/FakeProvider/FakeDbParameter.cs index f53d5ef4ddd..f65247491e6 100644 --- a/test/EFCore.Relational.Tests/TestUtilities/FakeProvider/FakeDbParameter.cs +++ b/test/EFCore.Relational.Tests/TestUtilities/FakeProvider/FakeDbParameter.cs @@ -2,14 +2,16 @@ // The .NET Foundation licenses this file to you under the MIT license. using System.Data; +using System.Diagnostics.CodeAnalysis; namespace Microsoft.EntityFrameworkCore.TestUtilities.FakeProvider; public class FakeDbParameter : DbParameter { - public override string ParameterName { get; set; } + [AllowNull] + public override string ParameterName { get; set; } = null!; - public override object Value { get; set; } + public override object? Value { get; set; } public override ParameterDirection Direction { get; set; } @@ -21,6 +23,7 @@ public class FakeDbParameter : DbParameter public override int Size { get; set; } + [AllowNull] public override string SourceColumn { get => throw new NotImplementedException(); diff --git a/test/EFCore.Relational.Tests/TestUtilities/FakeProvider/FakeRelationalConnection.cs b/test/EFCore.Relational.Tests/TestUtilities/FakeProvider/FakeRelationalConnection.cs index 712ce49a3f8..05e4b4034de 100644 --- a/test/EFCore.Relational.Tests/TestUtilities/FakeProvider/FakeRelationalConnection.cs +++ b/test/EFCore.Relational.Tests/TestUtilities/FakeProvider/FakeRelationalConnection.cs @@ -8,7 +8,7 @@ namespace Microsoft.EntityFrameworkCore.TestUtilities.FakeProvider; -public class FakeRelationalConnection(IDbContextOptions options = null) +public class FakeRelationalConnection(IDbContextOptions? options = null) : RelationalConnection( new RelationalConnectionDependencies( options ?? CreateOptions(), @@ -40,7 +40,7 @@ public class FakeRelationalConnection(IDbContextOptions options = null) new LoggingOptions())), new ExceptionDetector())) { - private DbConnection _connection; + private DbConnection? _connection; private readonly List _dbConnections = []; @@ -74,13 +74,13 @@ public List> ConnectionDiagnosticEvents protected override bool SupportsAmbientTransactions => true; - protected override void ConnectionEnlistTransaction(Transaction transaction) + protected override void ConnectionEnlistTransaction(Transaction? transaction) { } protected override DbConnection CreateDbConnection() { - var connection = new FakeDbConnection(ConnectionString); + var connection = new FakeDbConnection(ConnectionString!); _dbConnections.Add(connection); diff --git a/test/EFCore.Relational.Tests/TestUtilities/FakeProvider/FakeRelationalDbContextOptionsExtension.cs b/test/EFCore.Relational.Tests/TestUtilities/FakeProvider/FakeRelationalDbContextOptionsExtension.cs index 8199a6036d9..83dadea822d 100644 --- a/test/EFCore.Relational.Tests/TestUtilities/FakeProvider/FakeRelationalDbContextOptionsExtension.cs +++ b/test/EFCore.Relational.Tests/TestUtilities/FakeProvider/FakeRelationalDbContextOptionsExtension.cs @@ -7,19 +7,19 @@ public static class FakeRelationalDbContextOptionsExtension { public static DbContextOptionsBuilder UseFakeRelational( this DbContextOptionsBuilder optionsBuilder, - Action fakeRelationalOptionsAction = null) + Action? fakeRelationalOptionsAction = null) => optionsBuilder.UseFakeRelational("Database=Fake", fakeRelationalOptionsAction); public static DbContextOptionsBuilder UseFakeRelational( this DbContextOptionsBuilder optionsBuilder, string connectionString, - Action fakeRelationalOptionsAction = null) + Action? fakeRelationalOptionsAction = null) => optionsBuilder.UseFakeRelational(new FakeDbConnection(connectionString), fakeRelationalOptionsAction); public static DbContextOptionsBuilder UseFakeRelational( this DbContextOptionsBuilder optionsBuilder, DbConnection connection, - Action fakeRelationalOptionsAction = null) + Action? fakeRelationalOptionsAction = null) { var extension = (FakeRelationalOptionsExtension)GetOrCreateExtension(optionsBuilder).WithConnection(connection); ((IDbContextOptionsBuilderInfrastructure)optionsBuilder).AddOrUpdateExtension(extension); diff --git a/test/EFCore.Relational.Tests/TestUtilities/FakeProvider/FakeRelationalOptionsExtension.cs b/test/EFCore.Relational.Tests/TestUtilities/FakeProvider/FakeRelationalOptionsExtension.cs index c23460f4ea7..03a5f11f048 100644 --- a/test/EFCore.Relational.Tests/TestUtilities/FakeProvider/FakeRelationalOptionsExtension.cs +++ b/test/EFCore.Relational.Tests/TestUtilities/FakeProvider/FakeRelationalOptionsExtension.cs @@ -5,7 +5,7 @@ namespace Microsoft.EntityFrameworkCore.TestUtilities.FakeProvider; public class FakeRelationalOptionsExtension : RelationalOptionsExtension { - private DbContextOptionsExtensionInfo _info; + private DbContextOptionsExtensionInfo? _info; public FakeRelationalOptionsExtension() { @@ -35,7 +35,7 @@ public static IServiceCollection AddEntityFrameworkRelationalDatabase(IServiceCo .TryAdd() .TryAdd() .TryAdd() - .TryAdd(_ => null) + .TryAdd(_ => null!) .TryAdd() .TryAdd() .TryAdd() diff --git a/test/EFCore.Relational.Tests/TestUtilities/FakeRelationalCommandDiagnosticsLogger.cs b/test/EFCore.Relational.Tests/TestUtilities/FakeRelationalCommandDiagnosticsLogger.cs index a3bcdd28f7d..7d549728c85 100644 --- a/test/EFCore.Relational.Tests/TestUtilities/FakeRelationalCommandDiagnosticsLogger.cs +++ b/test/EFCore.Relational.Tests/TestUtilities/FakeRelationalCommandDiagnosticsLogger.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable - namespace Microsoft.EntityFrameworkCore.TestUtilities; public class FakeRelationalCommandDiagnosticsLogger diff --git a/test/EFCore.Relational.Tests/TestUtilities/ListDiagnosticSource.cs b/test/EFCore.Relational.Tests/TestUtilities/ListDiagnosticSource.cs index 9aafb484098..3b82c94df36 100644 --- a/test/EFCore.Relational.Tests/TestUtilities/ListDiagnosticSource.cs +++ b/test/EFCore.Relational.Tests/TestUtilities/ListDiagnosticSource.cs @@ -7,8 +7,8 @@ public class ListDiagnosticSource(List> diagnosticList) : { public List> DiagnosticList { get; } = diagnosticList; - public override void Write(string diagnosticName, object parameters) - => DiagnosticList?.Add(new Tuple(diagnosticName, parameters)); + public override void Write(string diagnosticName, object? parameters) + => DiagnosticList?.Add(new Tuple(diagnosticName, parameters!)); public override bool IsEnabled(string diagnosticName) => true; diff --git a/test/EFCore.Relational.Tests/TestUtilities/TestProviderCodeGenerator.cs b/test/EFCore.Relational.Tests/TestUtilities/TestProviderCodeGenerator.cs index dbbea8e5f75..acc6d9d3785 100644 --- a/test/EFCore.Relational.Tests/TestUtilities/TestProviderCodeGenerator.cs +++ b/test/EFCore.Relational.Tests/TestUtilities/TestProviderCodeGenerator.cs @@ -7,7 +7,7 @@ public class TestProviderCodeGenerator(ProviderCodeGeneratorDependencies depende { public override MethodCallCodeFragment GenerateUseProvider( string connectionString, - MethodCallCodeFragment providerOptions) + MethodCallCodeFragment? providerOptions) => new( _useTestProviderMethodInfo, providerOptions == null @@ -21,6 +21,6 @@ private static readonly MethodInfo _useTestProviderMethodInfo public static void UseTestProvider( DbContextOptionsBuilder optionsBuilder, string connectionString, - Action optionsAction = null) + Action? optionsAction = null) => throw new NotSupportedException(); } diff --git a/test/EFCore.Relational.Tests/TestUtilities/TestRelationalMigrationSqlGenerator.cs b/test/EFCore.Relational.Tests/TestUtilities/TestRelationalMigrationSqlGenerator.cs index 83914d531dc..5cfb07c1f45 100644 --- a/test/EFCore.Relational.Tests/TestUtilities/TestRelationalMigrationSqlGenerator.cs +++ b/test/EFCore.Relational.Tests/TestUtilities/TestRelationalMigrationSqlGenerator.cs @@ -5,35 +5,35 @@ namespace Microsoft.EntityFrameworkCore.TestUtilities; public class TestRelationalMigrationSqlGenerator(MigrationsSqlGeneratorDependencies dependencies) : MigrationsSqlGenerator(dependencies) { - protected override void Generate(RenameTableOperation operation, IModel model, MigrationCommandListBuilder builder) + protected override void Generate(RenameTableOperation operation, IModel? model, MigrationCommandListBuilder builder) { } protected override void Generate( DropIndexOperation operation, - IModel model, + IModel? model, MigrationCommandListBuilder builder, bool terminate = true) { } - protected override void Generate(RenameSequenceOperation operation, IModel model, MigrationCommandListBuilder builder) + protected override void Generate(RenameSequenceOperation operation, IModel? model, MigrationCommandListBuilder builder) { } - protected override void Generate(RenameColumnOperation operation, IModel model, MigrationCommandListBuilder builder) + protected override void Generate(RenameColumnOperation operation, IModel? model, MigrationCommandListBuilder builder) { } - protected override void Generate(EnsureSchemaOperation operation, IModel model, MigrationCommandListBuilder builder) + protected override void Generate(EnsureSchemaOperation operation, IModel? model, MigrationCommandListBuilder builder) { } - protected override void Generate(RenameIndexOperation operation, IModel model, MigrationCommandListBuilder builder) + protected override void Generate(RenameIndexOperation operation, IModel? model, MigrationCommandListBuilder builder) { } - protected override void Generate(AlterColumnOperation operation, IModel model, MigrationCommandListBuilder builder) + protected override void Generate(AlterColumnOperation operation, IModel? model, MigrationCommandListBuilder builder) { } } diff --git a/test/EFCore.Relational.Tests/TestUtilities/TestRelationalTypeMappingSource.cs b/test/EFCore.Relational.Tests/TestUtilities/TestRelationalTypeMappingSource.cs index c48c37afde4..1c1a62b60ad 100644 --- a/test/EFCore.Relational.Tests/TestUtilities/TestRelationalTypeMappingSource.cs +++ b/test/EFCore.Relational.Tests/TestUtilities/TestRelationalTypeMappingSource.cs @@ -148,7 +148,7 @@ protected override string ProcessStoreType( : storeType; } - protected override RelationalTypeMapping FindMapping(in RelationalTypeMappingInfo mappingInfo) + protected override RelationalTypeMapping? FindMapping(in RelationalTypeMappingInfo mappingInfo) { var clrType = mappingInfo.ClrType; var storeTypeName = mappingInfo.StoreTypeName; @@ -221,8 +221,8 @@ protected override RelationalTypeMapping FindMapping(in RelationalTypeMappingInf : null; } - protected override string ParseStoreTypeName( - string storeTypeName, + protected override string? ParseStoreTypeName( + string? storeTypeName, ref bool? unicode, ref int? size, ref int? precision, diff --git a/test/EFCore.Relational.Tests/Update/BatchExecutorTest.cs b/test/EFCore.Relational.Tests/Update/BatchExecutorTest.cs index 2c3536559e0..605d752cf34 100644 --- a/test/EFCore.Relational.Tests/Update/BatchExecutorTest.cs +++ b/test/EFCore.Relational.Tests/Update/BatchExecutorTest.cs @@ -73,17 +73,17 @@ private static readonly IServiceProvider _serviceProvider new ServiceCollection()) .BuildServiceProvider(validateScopes: true); - public DbSet Foos { get; set; } - public DbSet Bars { get; set; } + public DbSet Foos { get; set; } = null!; + public DbSet Bars { get; set; } = null!; } private class Foo { - public string Id { get; set; } + public string Id { get; set; } = null!; } private class Bar { - public string Id { get; set; } + public string Id { get; set; } = null!; } } diff --git a/test/EFCore.Relational.Tests/Update/CommandBatchPreparerTest.cs b/test/EFCore.Relational.Tests/Update/CommandBatchPreparerTest.cs index 47dee746e5a..401cbfd3746 100644 --- a/test/EFCore.Relational.Tests/Update/CommandBatchPreparerTest.cs +++ b/test/EFCore.Relational.Tests/Update/CommandBatchPreparerTest.cs @@ -37,7 +37,7 @@ public void BatchCommands_creates_valid_batch_for_added_entities() Assert.Equal("Id", columnMod.ColumnName); Assert.Same(entry, columnMod.Entry); - Assert.Equal("Id", columnMod.Property.Name); + Assert.Equal("Id", columnMod.Property!.Name); Assert.False(columnMod.IsCondition); Assert.True(columnMod.IsKey); Assert.False(columnMod.IsRead); @@ -47,7 +47,7 @@ public void BatchCommands_creates_valid_batch_for_added_entities() Assert.Equal("Value", columnMod.ColumnName); Assert.Same(entry, columnMod.Entry); - Assert.Equal("Value", columnMod.Property.Name); + Assert.Equal("Value", columnMod.Property!.Name); Assert.False(columnMod.IsCondition); Assert.False(columnMod.IsKey); Assert.False(columnMod.IsRead); @@ -78,7 +78,7 @@ public void BatchCommands_creates_valid_batch_for_modified_entities() Assert.Equal("Id", columnMod.ColumnName); Assert.Same(entry, columnMod.Entry); - Assert.Equal("Id", columnMod.Property.Name); + Assert.Equal("Id", columnMod.Property!.Name); Assert.True(columnMod.IsCondition); Assert.True(columnMod.IsKey); Assert.False(columnMod.IsRead); @@ -88,7 +88,7 @@ public void BatchCommands_creates_valid_batch_for_modified_entities() Assert.Equal("Value", columnMod.ColumnName); Assert.Same(entry, columnMod.Entry); - Assert.Equal("Value", columnMod.Property.Name); + Assert.Equal("Value", columnMod.Property!.Name); Assert.False(columnMod.IsCondition); Assert.False(columnMod.IsKey); Assert.False(columnMod.IsRead); @@ -119,7 +119,7 @@ public void BatchCommands_creates_valid_batch_for_deleted_entities() Assert.Equal("Id", columnMod.ColumnName); Assert.Same(entry, columnMod.Entry); - Assert.Equal("Id", columnMod.Property.Name); + Assert.Equal("Id", columnMod.Property!.Name); Assert.True(columnMod.IsCondition); Assert.True(columnMod.IsKey); Assert.False(columnMod.IsRead); @@ -260,7 +260,7 @@ public void BatchCommands_sorts_entities_when_reparenting() var relatedEntry = stateManager.GetOrCreateEntry( new RelatedFakeEntity { Id = 1, RelatedId = 3 }); relatedEntry.SetEntityState(EntityState.Modified); - relatedEntry.SetOriginalValue(relatedEntry.EntityType.FindProperty("RelatedId"), 42); + relatedEntry.SetOriginalValue(relatedEntry.EntityType.FindProperty("RelatedId")!, 42); var modelData = new UpdateAdapter(stateManager); @@ -352,7 +352,7 @@ public void BatchCommands_creates_batches_lazily() var relatedEntry = stateManager.GetOrCreateEntry(new RelatedFakeEntity { RelatedId = temporaryIdValue }); relatedEntry.SetEntityState(EntityState.Added); - var factory = (TestModificationCommandBatchFactory)configuration.GetService(); + var factory = (TestModificationCommandBatchFactory)configuration.GetService()!; var batches = CreateCommandBatchPreparer(factory).BatchCommands([relatedEntry, entry], new UpdateAdapter(stateManager)); @@ -389,7 +389,7 @@ public void Batch_command_does_not_order_non_unique_index_values() Value = "Test2" }); fakeEntry2.SetEntityState(EntityState.Modified); - fakeEntry2.SetOriginalValue(fakeEntry2.EntityType.FindProperty(nameof(FakeEntity.Value)), "Test"); + fakeEntry2.SetOriginalValue(fakeEntry2.EntityType.FindProperty(nameof(FakeEntity.Value))!, "Test"); var modelData = new UpdateAdapter(stateManager); @@ -414,7 +414,7 @@ public void BatchCommands_throws_on_non_store_generated_temporary_values() Assert.Equal( CoreStrings.TempValue(nameof(FakeEntity.Value), nameof(FakeEntity)), Assert.Throws(() => entry.SetTemporaryValue( - entry.EntityType.FindProperty(nameof(FakeEntity.Value)), "Test")).Message); + entry.EntityType.FindProperty(nameof(FakeEntity.Value))!, "Test")).Message); } [InlineData(true), InlineData(false), Theory] @@ -472,7 +472,7 @@ public void Batch_command_throws_on_commands_with_circular_dependencies_includin UniqueValue = "Test2" }); fakeEntry2.SetEntityState(EntityState.Modified); - fakeEntry2.SetOriginalValue(fakeEntry2.EntityType.FindProperty(nameof(FakeEntity.UniqueValue)), "Test"); + fakeEntry2.SetOriginalValue(fakeEntry2.EntityType.FindProperty(nameof(FakeEntity.UniqueValue))!, "Test"); var modelData = new UpdateAdapter(stateManager); @@ -544,7 +544,7 @@ public void BatchCommands_works_with_duplicate_values_for_unique_indexes() var fakeEntry2 = stateManager.GetOrCreateEntry( new FakeEntity { Id = 2, UniqueValue = "Test2" }); fakeEntry2.SetEntityState(EntityState.Modified); - fakeEntry2.SetOriginalValue(fakeEntry.EntityType.FindProperty(nameof(FakeEntity.UniqueValue)), "Test"); + fakeEntry2.SetOriginalValue(fakeEntry.EntityType.FindProperty(nameof(FakeEntity.UniqueValue))!, "Test"); var modelData = new UpdateAdapter(stateManager); @@ -575,7 +575,7 @@ public void BatchCommands_skips_unique_index_edges_for_unchanged_store_generated Payload = "new-basic" }); modifiedBasic.SetEntityState(EntityState.Modified); - modifiedBasic.SetOriginalValue(modifiedBasic.EntityType.FindProperty(nameof(CompositeKeyEntity.Payload)), "old-basic"); + modifiedBasic.SetOriginalValue(modifiedBasic.EntityType.FindProperty(nameof(CompositeKeyEntity.Payload))!, "old-basic"); var modifiedPro = stateManager.GetOrCreateEntry( new CompositeKeyEntity @@ -585,9 +585,9 @@ public void BatchCommands_skips_unique_index_edges_for_unchanged_store_generated Payload = "new-pro" }); modifiedPro.SetEntityState(EntityState.Modified); - modifiedPro.SetOriginalValue(modifiedPro.EntityType.FindProperty(nameof(CompositeKeyEntity.Payload)), "old-pro"); + modifiedPro.SetOriginalValue(modifiedPro.EntityType.FindProperty(nameof(CompositeKeyEntity.Payload))!, "old-pro"); - var clusteringKeyProperty = modifiedBasic.EntityType.FindProperty(nameof(CompositeKeyEntity.ClusteringKey)); + var clusteringKeyProperty = modifiedBasic.EntityType.FindProperty(nameof(CompositeKeyEntity.ClusteringKey))!; modifiedBasic.SetOriginalValue(clusteringKeyProperty, 0); modifiedPro.SetOriginalValue(clusteringKeyProperty, 0); @@ -1022,8 +1022,8 @@ public List CreateBatches( .ToList(); public ICommandBatchPreparer CreateCommandBatchPreparer( - IModificationCommandBatchFactory modificationCommandBatchFactory = null, - IUpdateAdapter updateAdapter = null, + IModificationCommandBatchFactory? modificationCommandBatchFactory = null, + IUpdateAdapter? updateAdapter = null, bool sensitiveLogging = false) { modificationCommandBatchFactory ??= @@ -1196,8 +1196,8 @@ private static IModel CreateCompositeKeyModelWithGeneratedUniqueIndex() private class FakeEntity { public int Id { get; set; } - public string Value { get; set; } - public string UniqueValue { get; set; } + public string Value { get; set; } = null!; + public string UniqueValue { get; set; } = null!; public int? RelatedId { get; set; } } @@ -1209,7 +1209,7 @@ private class RelatedFakeEntity private class DerivedRelatedFakeEntity : RelatedFakeEntity { - public string DerivedValue { get; set; } + public string DerivedValue { get; set; } = null!; } private class CompositeKeyEntity @@ -1217,7 +1217,7 @@ private class CompositeKeyEntity public Guid TestId { get; set; } public CompositeCategory Category { get; set; } public int ClusteringKey { get; set; } - public string Payload { get; set; } + public string Payload { get; set; } = null!; } private enum CompositeCategory @@ -1300,7 +1300,8 @@ public void BatchCommands_creates_valid_batch_for_replaced_entity_with_TPH_and_o entityAEntry.SetEntityState(EntityState.Unchanged); // Track the owned entity - var ownedEntityType = model.FindEntityType(typeof(OwnedEntity37588), "Owned", model.FindEntityType(typeof(EntityA37588))); + var ownedEntityType = model.FindEntityType( + typeof(OwnedEntity37588), "Owned", model.FindEntityType(typeof(EntityA37588))!)!; var ownedEntry = stateManager.GetOrCreateEntry(entityA.Owned, ownedEntityType); ownedEntry.SetEntityState(EntityState.Unchanged); @@ -1353,7 +1354,7 @@ public void BatchCommands_creates_valid_batch_for_replaced_entity_with_TPH_and_o private abstract class EntityBase37588 { - public string Id { get; set; } + public string Id { get; set; } = null!; public long RowVersion { get; set; } } @@ -1365,12 +1366,12 @@ private class OwnedEntity37588 private class EntityA37588 : EntityBase37588 { public bool SomeValue { get; set; } - public OwnedEntity37588 Owned { get; set; } + public OwnedEntity37588 Owned { get; set; } = null!; } private class EntityB37588 : EntityBase37588 { - public string Name { get; set; } + public string Name { get; set; } = null!; } private class AnotherFakeEntity @@ -1433,7 +1434,7 @@ private static IModel CreateTpcFKModel() modelBuilder.Entity() .UseTpcMappingStrategy() - .ToTable((string)null) + .ToTable((string?)null) .Property(e => e.Id) .ValueGeneratedNever(); diff --git a/test/EFCore.Relational.Tests/Update/ModificationCommandComparerTest.cs b/test/EFCore.Relational.Tests/Update/ModificationCommandComparerTest.cs index d470b3c9a8c..f5301582917 100644 --- a/test/EFCore.Relational.Tests/Update/ModificationCommandComparerTest.cs +++ b/test/EFCore.Relational.Tests/Update/ModificationCommandComparerTest.cs @@ -222,7 +222,7 @@ private enum FlagsEnum private static INonTrackedModificationCommand CreateModificationCommand( string name, - string schema, + string? schema, bool sensitiveLoggingEnabled) => CreateModificationCommandSource().CreateNonTrackedModificationCommand( new NonTrackedModificationCommandParameters(name, schema, sensitiveLoggingEnabled)); diff --git a/test/EFCore.Relational.Tests/Update/ModificationCommandTest.cs b/test/EFCore.Relational.Tests/Update/ModificationCommandTest.cs index bf777c02cff..3ce48a899f0 100644 --- a/test/EFCore.Relational.Tests/Update/ModificationCommandTest.cs +++ b/test/EFCore.Relational.Tests/Update/ModificationCommandTest.cs @@ -14,7 +14,7 @@ public class ModificationCommandTest public void ModificationCommand_initialized_correctly_for_added_entities_with_temp_generated_key() { var entry = CreateEntry(EntityState.Added, generateKeyValues: true); - entry.SetTemporaryValue(entry.EntityType.FindPrimaryKey().Properties[0], -1); + entry.SetTemporaryValue(entry.EntityType.FindPrimaryKey()!.Properties[0], -1); var command = CreateModificationCommand(entry, new ParameterNameGenerator().GenerateNext, false, null); command.AddEntry(entry, true); @@ -28,7 +28,7 @@ public void ModificationCommand_initialized_correctly_for_added_entities_with_te Assert.Equal("Col1", columnMod.ColumnName); Assert.Same(entry, columnMod.Entry); - Assert.Equal("Id", columnMod.Property.Name); + Assert.Equal("Id", columnMod.Property!.Name); Assert.False(columnMod.IsCondition); Assert.True(columnMod.IsKey); Assert.True(columnMod.IsRead); @@ -38,7 +38,7 @@ public void ModificationCommand_initialized_correctly_for_added_entities_with_te Assert.Equal("Col2", columnMod.ColumnName); Assert.Same(entry, columnMod.Entry); - Assert.Equal("Name1", columnMod.Property.Name); + Assert.Equal("Name1", columnMod.Property!.Name); Assert.False(columnMod.IsCondition); Assert.False(columnMod.IsKey); Assert.False(columnMod.IsRead); @@ -48,7 +48,7 @@ public void ModificationCommand_initialized_correctly_for_added_entities_with_te Assert.Equal("Col3", columnMod.ColumnName); Assert.Same(entry, columnMod.Entry); - Assert.Equal("Name2", columnMod.Property.Name); + Assert.Equal("Name2", columnMod.Property!.Name); Assert.False(columnMod.IsCondition); Assert.False(columnMod.IsKey); Assert.False(columnMod.IsRead); @@ -72,7 +72,7 @@ public void ModificationCommand_initialized_correctly_for_added_entities_with_no Assert.Equal("Col1", columnMod.ColumnName); Assert.Same(entry, columnMod.Entry); - Assert.Equal("Id", columnMod.Property.Name); + Assert.Equal("Id", columnMod.Property!.Name); Assert.False(columnMod.IsCondition); Assert.True(columnMod.IsKey); Assert.False(columnMod.IsRead); @@ -82,7 +82,7 @@ public void ModificationCommand_initialized_correctly_for_added_entities_with_no Assert.Equal("Col2", columnMod.ColumnName); Assert.Same(entry, columnMod.Entry); - Assert.Equal("Name1", columnMod.Property.Name); + Assert.Equal("Name1", columnMod.Property!.Name); Assert.False(columnMod.IsCondition); Assert.False(columnMod.IsKey); Assert.False(columnMod.IsRead); @@ -92,7 +92,7 @@ public void ModificationCommand_initialized_correctly_for_added_entities_with_no Assert.Equal("Col3", columnMod.ColumnName); Assert.Same(entry, columnMod.Entry); - Assert.Equal("Name2", columnMod.Property.Name); + Assert.Equal("Name2", columnMod.Property!.Name); Assert.False(columnMod.IsCondition); Assert.False(columnMod.IsKey); Assert.False(columnMod.IsRead); @@ -116,7 +116,7 @@ public void ModificationCommand_initialized_correctly_for_added_entities_with_ex Assert.Equal("Col1", columnMod.ColumnName); Assert.Same(entry, columnMod.Entry); - Assert.Equal("Id", columnMod.Property.Name); + Assert.Equal("Id", columnMod.Property!.Name); Assert.False(columnMod.IsCondition); Assert.True(columnMod.IsKey); Assert.False(columnMod.IsRead); @@ -126,7 +126,7 @@ public void ModificationCommand_initialized_correctly_for_added_entities_with_ex Assert.Equal("Col2", columnMod.ColumnName); Assert.Same(entry, columnMod.Entry); - Assert.Equal("Name1", columnMod.Property.Name); + Assert.Equal("Name1", columnMod.Property!.Name); Assert.False(columnMod.IsCondition); Assert.False(columnMod.IsKey); Assert.False(columnMod.IsRead); @@ -136,7 +136,7 @@ public void ModificationCommand_initialized_correctly_for_added_entities_with_ex Assert.Equal("Col3", columnMod.ColumnName); Assert.Same(entry, columnMod.Entry); - Assert.Equal("Name2", columnMod.Property.Name); + Assert.Equal("Name2", columnMod.Property!.Name); Assert.False(columnMod.IsCondition); Assert.False(columnMod.IsKey); Assert.False(columnMod.IsRead); @@ -160,7 +160,7 @@ public void ModificationCommand_initialized_correctly_for_modified_entities_with Assert.Equal("Col1", columnMod.ColumnName); Assert.Same(entry, columnMod.Entry); - Assert.Equal("Id", columnMod.Property.Name); + Assert.Equal("Id", columnMod.Property!.Name); Assert.True(columnMod.IsCondition); Assert.True(columnMod.IsKey); Assert.False(columnMod.IsRead); @@ -170,7 +170,7 @@ public void ModificationCommand_initialized_correctly_for_modified_entities_with Assert.Equal("Col2", columnMod.ColumnName); Assert.Same(entry, columnMod.Entry); - Assert.Equal("Name1", columnMod.Property.Name); + Assert.Equal("Name1", columnMod.Property!.Name); Assert.False(columnMod.IsCondition); Assert.False(columnMod.IsKey); Assert.False(columnMod.IsRead); @@ -180,7 +180,7 @@ public void ModificationCommand_initialized_correctly_for_modified_entities_with Assert.Equal("Col3", columnMod.ColumnName); Assert.Same(entry, columnMod.Entry); - Assert.Equal("Name2", columnMod.Property.Name); + Assert.Equal("Name2", columnMod.Property!.Name); Assert.False(columnMod.IsCondition); Assert.False(columnMod.IsKey); Assert.False(columnMod.IsRead); @@ -204,7 +204,7 @@ public void ModificationCommand_initialized_correctly_for_modified_entities_with Assert.Equal("Col1", columnMod.ColumnName); Assert.Same(entry, columnMod.Entry); - Assert.Equal("Id", columnMod.Property.Name); + Assert.Equal("Id", columnMod.Property!.Name); Assert.True(columnMod.IsCondition); Assert.True(columnMod.IsKey); Assert.False(columnMod.IsRead); @@ -214,7 +214,7 @@ public void ModificationCommand_initialized_correctly_for_modified_entities_with Assert.Equal("Col2", columnMod.ColumnName); Assert.Same(entry, columnMod.Entry); - Assert.Equal("Name1", columnMod.Property.Name); + Assert.Equal("Name1", columnMod.Property!.Name); Assert.False(columnMod.IsCondition); Assert.False(columnMod.IsKey); Assert.False(columnMod.IsRead); @@ -224,7 +224,7 @@ public void ModificationCommand_initialized_correctly_for_modified_entities_with Assert.Equal("Col3", columnMod.ColumnName); Assert.Same(entry, columnMod.Entry); - Assert.Equal("Name2", columnMod.Property.Name); + Assert.Equal("Name2", columnMod.Property!.Name); Assert.False(columnMod.IsCondition); Assert.False(columnMod.IsKey); Assert.False(columnMod.IsRead); @@ -248,7 +248,7 @@ public void ModificationCommand_initialized_correctly_for_modified_entities_with Assert.Equal("Col1", columnMod.ColumnName); Assert.Same(entry, columnMod.Entry); - Assert.Equal("Id", columnMod.Property.Name); + Assert.Equal("Id", columnMod.Property!.Name); Assert.True(columnMod.IsCondition); Assert.True(columnMod.IsKey); Assert.False(columnMod.IsRead); @@ -258,7 +258,7 @@ public void ModificationCommand_initialized_correctly_for_modified_entities_with Assert.Equal("Col2", columnMod.ColumnName); Assert.Same(entry, columnMod.Entry); - Assert.Equal("Name1", columnMod.Property.Name); + Assert.Equal("Name1", columnMod.Property!.Name); Assert.True(columnMod.IsCondition); Assert.False(columnMod.IsKey); Assert.True(columnMod.IsRead); @@ -268,7 +268,7 @@ public void ModificationCommand_initialized_correctly_for_modified_entities_with Assert.Equal("Col3", columnMod.ColumnName); Assert.Same(entry, columnMod.Entry); - Assert.Equal("Name2", columnMod.Property.Name); + Assert.Equal("Name2", columnMod.Property!.Name); Assert.True(columnMod.IsCondition); Assert.False(columnMod.IsKey); Assert.True(columnMod.IsRead); @@ -292,7 +292,7 @@ public void ModificationCommand_initialized_correctly_for_deleted_entities() Assert.Equal("Col1", columnMod.ColumnName); Assert.Same(entry, columnMod.Entry); - Assert.Equal("Id", columnMod.Property.Name); + Assert.Equal("Id", columnMod.Property!.Name); Assert.True(columnMod.IsCondition); Assert.True(columnMod.IsKey); Assert.False(columnMod.IsRead); @@ -316,7 +316,7 @@ public void ModificationCommand_initialized_correctly_for_deleted_entities_with_ Assert.Equal("Col1", columnMod.ColumnName); Assert.Same(entry, columnMod.Entry); - Assert.Equal("Id", columnMod.Property.Name); + Assert.Equal("Id", columnMod.Property!.Name); Assert.True(columnMod.IsCondition); Assert.True(columnMod.IsKey); Assert.False(columnMod.IsRead); @@ -326,7 +326,7 @@ public void ModificationCommand_initialized_correctly_for_deleted_entities_with_ Assert.Equal("Col2", columnMod.ColumnName); Assert.Same(entry, columnMod.Entry); - Assert.Equal("Name1", columnMod.Property.Name); + Assert.Equal("Name1", columnMod.Property!.Name); Assert.True(columnMod.IsCondition); Assert.False(columnMod.IsKey); Assert.False(columnMod.IsRead); @@ -336,7 +336,7 @@ public void ModificationCommand_initialized_correctly_for_deleted_entities_with_ Assert.Equal("Col3", columnMod.ColumnName); Assert.Same(entry, columnMod.Entry); - Assert.Equal("Name2", columnMod.Property.Name); + Assert.Equal("Name2", columnMod.Property!.Name); Assert.True(columnMod.IsCondition); Assert.False(columnMod.IsKey); Assert.False(columnMod.IsRead); @@ -374,8 +374,8 @@ public void ModificationCommand_throws_for_unknown_entities(bool sensitive) private class T1 { public int Id { get; set; } - public string Name1 { get; set; } - public string Name2 { get; set; } + public string? Name1 { get; set; } + public string? Name2 { get; set; } } private static IModel BuildModel(bool generateKeyValues, bool computeNonKeyValue) @@ -384,18 +384,18 @@ private static IModel BuildModel(bool generateKeyValues, bool computeNonKeyValue var model = modelBuilder.Model; var entityType = model.AddEntityType(typeof(T1)); - var key = entityType.FindProperty("Id"); + var key = entityType.FindProperty("Id")!; key.ValueGenerated = generateKeyValues ? ValueGenerated.OnAdd : ValueGenerated.Never; key.SetColumnName("Col1"); entityType.SetPrimaryKey(key); - var nonKey1 = entityType.FindProperty("Name1"); + var nonKey1 = entityType.FindProperty("Name1")!; nonKey1.IsConcurrencyToken = computeNonKeyValue; nonKey1.SetColumnName("Col2"); nonKey1.ValueGenerated = computeNonKeyValue ? ValueGenerated.OnAddOrUpdate : ValueGenerated.Never; - var nonKey2 = entityType.FindProperty("Name2"); + var nonKey2 = entityType.FindProperty("Name2")!; nonKey2.IsConcurrencyToken = computeNonKeyValue; nonKey2.SetColumnName("Col3"); @@ -427,7 +427,7 @@ private static IModificationCommand CreateModificationCommand( InternalEntityEntry entry, Func generateParameterName, bool sensitiveLoggingEnabled, - IComparer comparer) + IComparer? comparer) => new ModificationCommandFactory().CreateModificationCommand( new ModificationCommandParameters( entry.EntityType.GetTableMappings().Single().Table, diff --git a/test/EFCore.Relational.Tests/Update/ReaderModificationCommandBatchTest.cs b/test/EFCore.Relational.Tests/Update/ReaderModificationCommandBatchTest.cs index d91ad84cdde..7a66e049f0e 100644 --- a/test/EFCore.Relational.Tests/Update/ReaderModificationCommandBatchTest.cs +++ b/test/EFCore.Relational.Tests/Update/ReaderModificationCommandBatchTest.cs @@ -258,7 +258,7 @@ public async Task ExecuteAsync_executes_batch_commands_and_consumes_reader() public async Task ExecuteAsync_saves_store_generated_values() { var entry = CreateEntry(EntityState.Added, generateKeyValues: true); - entry.SetTemporaryValue(entry.EntityType.FindPrimaryKey().Properties[0], -1); + entry.SetTemporaryValue(entry.EntityType.FindPrimaryKey()!.Properties[0], -1); var command = CreateModificationCommand(entry, new ParameterNameGenerator().GenerateNext, true, null); command.AddEntry(entry, true); @@ -273,8 +273,8 @@ public async Task ExecuteAsync_saves_store_generated_values() await batch.ExecuteAsync(connection); - Assert.Equal(42, entry[entry.EntityType.FindProperty("Id")]); - Assert.Equal("Test", entry[entry.EntityType.FindProperty("Name")]); + Assert.Equal(42, entry[entry.EntityType.FindProperty("Id")!]); + Assert.Equal("Test", entry[entry.EntityType.FindProperty("Name")!]); } [Fact] @@ -282,7 +282,7 @@ public async Task ExecuteAsync_saves_store_generated_values_on_non_key_columns() { var entry = CreateEntry( EntityState.Added, generateKeyValues: true, computeNonKeyValue: true); - entry.SetTemporaryValue(entry.EntityType.FindPrimaryKey().Properties[0], -1); + entry.SetTemporaryValue(entry.EntityType.FindPrimaryKey()!.Properties[0], -1); var command = CreateModificationCommand(entry, new ParameterNameGenerator().GenerateNext, true, null); command.AddEntry(entry, true); @@ -297,8 +297,8 @@ public async Task ExecuteAsync_saves_store_generated_values_on_non_key_columns() await batch.ExecuteAsync(connection); - Assert.Equal(42, entry[entry.EntityType.FindProperty("Id")]); - Assert.Equal("FortyTwo", entry[entry.EntityType.FindProperty("Name")]); + Assert.Equal(42, entry[entry.EntityType.FindProperty("Id")!]); + Assert.Equal("FortyTwo", entry[entry.EntityType.FindProperty("Name")!]); } [Fact] @@ -320,15 +320,15 @@ public async Task ExecuteAsync_saves_store_generated_values_when_updating() await batch.ExecuteAsync(connection); - Assert.Equal(1, entry[entry.EntityType.FindProperty("Id")]); - Assert.Equal("FortyTwo", entry[entry.EntityType.FindProperty("Name")]); + Assert.Equal(1, entry[entry.EntityType.FindProperty("Id")!]); + Assert.Equal("FortyTwo", entry[entry.EntityType.FindProperty("Name")!]); } [Fact] public async Task Exception_not_thrown_for_more_than_one_row_returned_for_single_command() { var entry = CreateEntry(EntityState.Added, generateKeyValues: true); - entry.SetTemporaryValue(entry.EntityType.FindPrimaryKey().Properties[0], -1); + entry.SetTemporaryValue(entry.EntityType.FindPrimaryKey()!.Properties[0], -1); var command = CreateModificationCommand(entry, new ParameterNameGenerator().GenerateNext, true, null); command.AddEntry(entry, true); @@ -344,7 +344,7 @@ public async Task Exception_not_thrown_for_more_than_one_row_returned_for_single await batch.ExecuteAsync(connection); - Assert.Equal(42, entry[entry.EntityType.FindProperty("Id")]); + Assert.Equal(42, entry[entry.EntityType.FindProperty("Id")!]); } [Theory, InlineData(false), InlineData(true)] @@ -374,7 +374,7 @@ public async Task Exception_thrown_if_rows_returned_for_command_without_store_ge public async Task Exception_thrown_if_no_rows_returned_for_command_with_store_generated_values(bool async) { var entry = CreateEntry(EntityState.Added, generateKeyValues: true); - entry.SetTemporaryValue(entry.EntityType.FindPrimaryKey().Properties[0], -1); + entry.SetTemporaryValue(entry.EntityType.FindPrimaryKey()!.Properties[0], -1); var command = CreateModificationCommand(entry, new ParameterNameGenerator().GenerateNext, true, null); command.AddEntry(entry, true); @@ -449,7 +449,7 @@ public async Task OperationCanceledException_is_not_wrapped_with_DbUpdateExcepti public void CreateStoreCommand_creates_parameters_for_each_ModificationCommand() { var entry = CreateEntry(EntityState.Added, generateKeyValues: true); - var property = entry.EntityType.FindProperty("Id"); + var property = entry.EntityType.FindProperty("Id")!; entry.SetTemporaryValue(property, 1); var batch = new ModificationCommandBatchFake(); @@ -502,7 +502,7 @@ public void CreateStoreCommand_creates_parameters_for_each_ModificationCommand() public void PopulateParameters_creates_parameter_for_write_ModificationCommand() { var entry = CreateEntry(EntityState.Added, generateKeyValues: true); - var property = entry.EntityType.FindProperty("Id"); + var property = entry.EntityType.FindProperty("Id")!; entry.SetTemporaryValue(property, 1); var batch = new ModificationCommandBatchFake(); @@ -538,7 +538,7 @@ public void PopulateParameters_creates_parameter_for_write_ModificationCommand() public void PopulateParameters_creates_parameter_for_condition_ModificationCommand() { var entry = CreateEntry(EntityState.Added, generateKeyValues: true); - var property = entry.EntityType.FindProperty("Id"); + var property = entry.EntityType.FindProperty("Id")!; entry.SetTemporaryValue(property, 1); var batch = new ModificationCommandBatchFake(); @@ -574,7 +574,7 @@ public void PopulateParameters_creates_parameter_for_condition_ModificationComma public void PopulateParameters_creates_parameters_for_write_and_condition_ModificationCommand() { var entry = CreateEntry(EntityState.Added, generateKeyValues: true); - var property = entry.EntityType.FindProperty("Id"); + var property = entry.EntityType.FindProperty("Id")!; entry.SetTemporaryValue(property, 1); var batch = new ModificationCommandBatchFake(); @@ -612,7 +612,7 @@ public void PopulateParameters_creates_parameters_for_write_and_condition_Modifi public void PopulateParameters_does_not_create_parameter_for_read_ModificationCommand() { var entry = CreateEntry(EntityState.Added, generateKeyValues: true); - var property = entry.EntityType.FindProperty("Id"); + var property = entry.EntityType.FindProperty("Id")!; entry.SetTemporaryValue(property, -1); var batch = new ModificationCommandBatchFake(); @@ -643,7 +643,7 @@ public void PopulateParameters_does_not_create_parameter_for_read_ModificationCo private class T1 { public int Id { get; set; } - public string Name { get; set; } + public string? Name { get; set; } } private static IModel BuildModel(bool generateKeyValues, bool computeNonKeyValue) @@ -678,7 +678,7 @@ private static InternalEntityEntry CreateEntry( model, entityState, new T1 { Id = overrideKeyValues ? 1 : default, Name = computeNonKeyValue ? null : "Test" }); } - private static FakeDbDataReader CreateFakeDataReader(string[] columnNames = null, IList results = null) + private static FakeDbDataReader CreateFakeDataReader(string[]? columnNames = null, IList? results = null) { results ??= [new object[] { 1 }]; columnNames ??= ["RowsAffected"]; @@ -688,7 +688,7 @@ private static FakeDbDataReader CreateFakeDataReader(string[] columnNames = null private class ModificationCommandBatchFake : AffectedCountModificationCommandBatch { - public ModificationCommandBatchFake(IUpdateSqlGenerator sqlGenerator = null, int? maxBatchSize = null) + public ModificationCommandBatchFake(IUpdateSqlGenerator? sqlGenerator = null, int? maxBatchSize = null) : base(CreateDependencies(sqlGenerator), maxBatchSize) { ShouldBeValid = true; @@ -697,7 +697,7 @@ public ModificationCommandBatchFake(IUpdateSqlGenerator sqlGenerator = null, int } private static ModificationCommandBatchFactoryDependencies CreateDependencies( - IUpdateSqlGenerator sqlGenerator) + IUpdateSqlGenerator? sqlGenerator) { var typeMappingSource = new TestRelationalTypeMappingSource( TestServiceFactory.Instance.Create(), @@ -732,7 +732,7 @@ protected override bool IsValid() => ShouldBeValid; public new RawSqlCommand StoreCommand - => base.StoreCommand; + => base.StoreCommand!; public FakeSqlGenerator FakeSqlGenerator => field ?? throw new InvalidOperationException("Not using FakeSqlGenerator"); @@ -754,10 +754,10 @@ private static FakeRelationalConnection CreateConnection(DbDataReader dbDataRead executeReaderAsync: (c, b, ct) => Task.FromResult(dbDataReader), executeReader: (c, b) => dbDataReader)); - private static FakeRelationalConnection CreateConnection(IDbContextOptions options = null) + private static FakeRelationalConnection CreateConnection(IDbContextOptions? options = null) => new(options ?? CreateOptions()); - public static IDbContextOptions CreateOptions(RelationalOptionsExtension optionsExtension = null) + public static IDbContextOptions CreateOptions(RelationalOptionsExtension? optionsExtension = null) { var optionsBuilder = new DbContextOptionsBuilder(); @@ -773,7 +773,7 @@ private static IModificationCommand CreateModificationCommand( InternalEntityEntry entry, Func generateParameterName, bool sensitiveLoggingEnabled, - IComparer comparer) + IComparer? comparer) { var modificationCommandParameters = new ModificationCommandParameters( entry.EntityType.GetTableMappings().Single().Table, @@ -787,7 +787,7 @@ private static IModificationCommand CreateModificationCommand( private static INonTrackedModificationCommand CreateModificationCommand( string name, - string schema, + string? schema, bool sensitiveLoggingEnabled, IReadOnlyList columnModifications) { diff --git a/test/EFCore.Relational.Tests/ValueGeneration/TemporaryBinaryValueGeneratorTest.cs b/test/EFCore.Relational.Tests/ValueGeneration/TemporaryBinaryValueGeneratorTest.cs index b9b82fe0441..7306d7c4d24 100644 --- a/test/EFCore.Relational.Tests/ValueGeneration/TemporaryBinaryValueGeneratorTest.cs +++ b/test/EFCore.Relational.Tests/ValueGeneration/TemporaryBinaryValueGeneratorTest.cs @@ -15,7 +15,7 @@ public void Creates_GUID_arrays() var values = new HashSet(); for (var i = 0; i < 100; i++) { - var generatedValue = generator.Next(null); + var generatedValue = generator.Next(null!); values.Add(new Guid(generatedValue)); } diff --git a/test/EFCore.Relational.Tests/ValueGeneration/TemporaryDateTimeOffsetValueGeneratorTest.cs b/test/EFCore.Relational.Tests/ValueGeneration/TemporaryDateTimeOffsetValueGeneratorTest.cs index 32dedb683bf..18271004f28 100644 --- a/test/EFCore.Relational.Tests/ValueGeneration/TemporaryDateTimeOffsetValueGeneratorTest.cs +++ b/test/EFCore.Relational.Tests/ValueGeneration/TemporaryDateTimeOffsetValueGeneratorTest.cs @@ -11,8 +11,8 @@ public class TemporaryDateTimeOffsetValueGeneratorTest public void Can_create_values_for_DateTime_types() { var generator = new TemporaryDateTimeOffsetValueGenerator(); - Assert.Equal(new DateTimeOffset(1, TimeSpan.Zero), generator.Next(null)); - Assert.Equal(new DateTimeOffset(2, TimeSpan.Zero), generator.Next(null)); + Assert.Equal(new DateTimeOffset(1, TimeSpan.Zero), generator.Next(null!)); + Assert.Equal(new DateTimeOffset(2, TimeSpan.Zero), generator.Next(null!)); } [Fact] diff --git a/test/EFCore.Relational.Tests/ValueGeneration/TemporaryDateTimeValueGeneratorTest.cs b/test/EFCore.Relational.Tests/ValueGeneration/TemporaryDateTimeValueGeneratorTest.cs index 23e6e7de09a..3ca5a4cf62e 100644 --- a/test/EFCore.Relational.Tests/ValueGeneration/TemporaryDateTimeValueGeneratorTest.cs +++ b/test/EFCore.Relational.Tests/ValueGeneration/TemporaryDateTimeValueGeneratorTest.cs @@ -12,8 +12,8 @@ public void Can_create_values_for_DateTime_types() { var generator = new TemporaryDateTimeValueGenerator(); - Assert.Equal(new DateTime(1), generator.Next(null)); - Assert.Equal(new DateTime(2), generator.Next(null)); + Assert.Equal(new DateTime(1), generator.Next(null!)); + Assert.Equal(new DateTime(2), generator.Next(null!)); } [Fact] diff --git a/test/EFCore.Relational.Tests/ValueGeneration/TemporaryStringValueGeneratorTest.cs b/test/EFCore.Relational.Tests/ValueGeneration/TemporaryStringValueGeneratorTest.cs index b98acf4f8f4..094b57de4b3 100644 --- a/test/EFCore.Relational.Tests/ValueGeneration/TemporaryStringValueGeneratorTest.cs +++ b/test/EFCore.Relational.Tests/ValueGeneration/TemporaryStringValueGeneratorTest.cs @@ -15,7 +15,7 @@ public void Creates_GUID_strings() var values = new HashSet(); for (var i = 0; i < 100; i++) { - var generatedValue = generator.Next(null); + var generatedValue = generator.Next(null!); values.Add(Guid.Parse(generatedValue)); } diff --git a/test/EFCore.Specification.Tests/Query/NorthwindDbFunctionsQueryTestBase.cs b/test/EFCore.Specification.Tests/Query/NorthwindDbFunctionsQueryTestBase.cs index 0441352dcdc..9410a91e782 100644 --- a/test/EFCore.Specification.Tests/Query/NorthwindDbFunctionsQueryTestBase.cs +++ b/test/EFCore.Specification.Tests/Query/NorthwindDbFunctionsQueryTestBase.cs @@ -16,7 +16,7 @@ public virtual Task Like_literal(bool async) ss => ss.Set(), ss => ss.Set(), c => EF.Functions.Like(c.ContactName, "%M%"), - c => c.ContactName.Contains("M") || c.ContactName.Contains("m")); + c => c.ContactName!.Contains("M") || c.ContactName.Contains("m")); [Theory, MemberData(nameof(IsAsyncData))] public virtual Task Like_identity(bool async) @@ -34,7 +34,7 @@ public virtual Task Like_literal_with_escape(bool async) ss => ss.Set(), ss => ss.Set(), c => EF.Functions.Like(c.ContactName, "!%", "!"), - c => c.ContactName.Contains("%")); + c => c.ContactName!.Contains("%")); [Theory, MemberData(nameof(IsAsyncData))] public virtual Task Like_all_literals(bool async) diff --git a/test/EFCore.Specification.Tests/TestModels/Northwind/Customer.cs b/test/EFCore.Specification.Tests/TestModels/Northwind/Customer.cs index b00d3177600..e7c809ac77d 100644 --- a/test/EFCore.Specification.Tests/TestModels/Northwind/Customer.cs +++ b/test/EFCore.Specification.Tests/TestModels/Northwind/Customer.cs @@ -9,8 +9,6 @@ namespace Microsoft.EntityFrameworkCore.TestModels.Northwind; -#nullable disable - public class Customer : IComparable { public Customer() @@ -22,42 +20,42 @@ public Customer(DbContext context, ILazyLoader lazyLoader, string customerID) => CustomerID = customerID; [MaxLength(5), Required] - public string CustomerID { get; set; } + public string CustomerID { get; set; } = null!; [MaxLength(40), Required] - public string CompanyName { get; set; } + public string CompanyName { get; set; } = null!; [MaxLength(30)] - public string ContactName { get; set; } + public string? ContactName { get; set; } [MaxLength(30)] - public string ContactTitle { get; set; } + public string? ContactTitle { get; set; } [MaxLength(60)] - public string Address { get; set; } + public string? Address { get; set; } [MaxLength(15)] - public string City { get; set; } + public string? City { get; set; } [MaxLength(15)] - public string Region { get; set; } + public string? Region { get; set; } [MaxLength(10)] - public string PostalCode { get; set; } + public string? PostalCode { get; set; } [MaxLength(15)] - public string Country { get; set; } + public string? Country { get; set; } [MaxLength(24)] - public string Phone { get; set; } + public string? Phone { get; set; } [MaxLength(24)] - public string Fax { get; set; } + public string? Fax { get; set; } - public virtual List Orders { get; set; } + public virtual List Orders { get; set; } = null!; [JsonIgnore, Newtonsoft.Json.JsonIgnore] - public NorthwindContext Context { get; set; } + public NorthwindContext Context { get; set; } = null!; [NotMapped] public bool IsLondon @@ -66,19 +64,19 @@ public bool IsLondon protected bool Equals(Customer other) => string.Equals(CustomerID, other.CustomerID); - public override bool Equals(object obj) + public override bool Equals(object? obj) => obj is not null && (ReferenceEquals(this, obj) || (obj.GetType() == GetType() && Equals((Customer)obj))); - public static bool operator ==(Customer left, Customer right) + public static bool operator ==(Customer? left, Customer? right) => Equals(left, right); - public static bool operator !=(Customer left, Customer right) + public static bool operator !=(Customer? left, Customer? right) => !Equals(left, right); - public int CompareTo(Customer other) + public int CompareTo(Customer? other) => other == null ? 1 : CustomerID.CompareTo(other.CustomerID); public override int GetHashCode()