Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.Net Core Fluent API with Nullable references types

I can't seem to solve the following problem and can't find anything online that helps. I'm new to .Net Core and am also new to using nullable reference types and somehow I can't make them work together with EF Core. I have a data table that includes a One to Many relationship where the foreign key is nullable (i.e. it's possible that there are no items in the relationship - in this example not all Assets have AssetTypes). The fluent API which used to work was

modelBuilder.Entity<Asset>(entity =>
{
    entity.HasOne(d => d.AssetType)
          .WithMany(p => p.Assets)
          .HasForeignKey(d => d.AssetTypeId)
          .HasConstraintName("FK_Assets_AssetTypes");}

The problem is since AssetType? is nullable I'm now getting a

'p' may be null here...warning on p.Assets

and can't seem to find a way around it short of suppressing the message and hoping it works, which it seems to although other Many to Many relationships do not and need to be dealt with manually. EFCore appears to be quite primitive on Many to Many unless I'm doing it wrong.

I have tried reversing the relationship by starting with the AssetType entity but I get a similar result.

I've also tried using

.WithMany() 

but this removes an existing navigation property and so it doesn't work.

Any help would be appreciated as I'm obviously missing something.

like image 986
Mark Avatar asked Feb 27 '26 19:02

Mark


1 Answers

I just encountered similar situation when configuring mapping expression. In the end, I decided to silence the warning, because the expression as written is never executed. It is only parsed by EF to do it's internal magic. In your case it would be like this (no need to deal with #pragma warning disable)

modelBuilder.Entity<Asset>(entity =>
{
    entity.HasOne(d => d.AssetType)
          .WithMany(p => p.Assets!)
                              // ^ this '!' tells to compiler to stop bothering you about this
                              // null dereference because you are sure the code is right
          .HasForeignKey(d => d.AssetTypeId)
          .HasConstraintName("FK_Assets_AssetTypes");
}
like image 126
huancz Avatar answered Mar 02 '26 15:03

huancz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!