简体   繁体   中英

Upgraded to .NET 6, having issues with EF - SqlNullValueException: 'Data is Null. This method or property cannot be called on Null values.'

I keep getting this error while querying on an entity that has a Nullable foreign key reference.

I have tried enabling and disabling nullable reference types (NRT) on the project but no luck.

It works when JobId is not null value and throws an exception when it's NULL.

My entity looks like this:

public class Employee 
{
    [DataMember]
    public Guid Id { get; set; }
    
    [DataMember]
    public string Name { get; set; }

    [DataMember]
    public Guid? JobId { get; set; }
  
    [DataMember]
    [ForeignKey("JobId")]
    public virtual Job JobDetails { get; set; }
}

Any inputs here, please?

Error:

System.Data.SqlTypes.SqlNullValueException: 'Data is Null. This method or property cannot be called on Null values.'

StackTrace:

at Microsoft.Data.SqlClient.SqlBuffer.get_Guid()
at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable 1.Enumerator.MoveNext() at System.Linq.Enumerable.TryGetSingle[TSource](IEnumerable 1 source, Boolean& found)
at System.Linq.Queryable.FirstOrDefault[TSource](IQueryable`1 source)

I have a couple of notes: according to entityframeworktutorial.net , you're not applying the ForeignKey attribute properly, the [ForeignKey] should be applied to the key property, not the other way around:

[DataMember]
[ForeignKey("JobDetails")] // You're telling JobId is the foreign key for JobDetails 
public Guid? JobId { get; set; }

[DataMember]    
public virtual Job JobDetails { get; set; }

Then, it's worth mentioning that you need the ForeignKey attribute only if the property name does NOT match the reference property name. So, if your Job entity class has a primary key property named JobId (exact match), you don't need the JobId property on Employee, at all.

Then, on some personal notes, I'm also wondering if you have added an ICollection property to the Job entity, and also if it's necessary to define and if it's necessary to define JobDetails as virtual...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM