New optional Foreign Key triggers Exception when querying
Hello there!
I ran into an issue that I don't understand, therefore here I am.
Here is my model:
public class Property : FullAuditedEntity<Guid>, IMayHaveTenant
{
public int? TenantId { get; set; }
[Required]
[StringLength(PropertyConsts.MaxNameLength, MinimumLength = PropertyConsts.MinNameLength)]
public virtual string Name { get; set; }
[Required]
public virtual Guid AddressId { get; set; }
[ForeignKey("AddressId")]
public Address AddressFk { get; set; }
public virtual Guid GridId { get; set; }
[ForeignKey("GridId")]
public Grid GridFk { get; set; }
}
I added the last part about GridId today and created a migration for it. Here it is:
migrationBuilder.AddColumn<Guid>(
name: "GridId",
table: "Properties",
type: "uniqueidentifier",
nullable: true,
defaultValue: null);
migrationBuilder.AddForeignKey(
name: "FK_Properties_Grids_GridId",
table: "Properties",
column: "GridId",
principalTable: "Grids",
principalColumn: "Id",
onDelete: ReferentialAction.NoAction);
Migration went well and the foreign key was created.
But now, when seeding my database, the following query triggers an error:
Property prop2 = _context.Properties.IgnoreQueryFilters().FirstOrDefault(p => p.Name == propertyName);
And the error is:
System.Data.SqlTypes.SqlNullValueException : 'Data is Null. This method or property cannot be called on Null values.'
à Microsoft.Data.SqlClient.SqlBuffer.ThrowIfNull()
à Microsoft.Data.SqlClient.SqlBuffer.get_Guid()
à Microsoft.Data.SqlClient.SqlDataReader.GetGuid(Int32 i)
à Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable`1.Enumerator.MoveNext()
à System.Linq.Enumerable.TryGetSingle[TSource](IEnumerable`1 source, Boolean& found)
à Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.Execute[TResult](Expression query)
à Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryProvider.Execute[TResult](Expression expression)
à System.Linq.Queryable.FirstOrDefault[TSource](IQueryable`1 source, Expression`1 predicate)
As I understand, the new column is somehow expected to hold a value, even though it is defined as nullable.
Does someone understand what it's all about?