How to debug and fix 'Nullable object must have a value' within Entity Framework Core?

.net c# entity-framework-core nullable

Question

I'm doing a projection in this method:

public async Task<TradeDetail> Get(int tradeId)
{
    var firstOrDefaultAsync = await context.EvgTGTrade
        .Where(x => x.IdTrade == tradeId)
        .Select(trade => new TradeDetail
        {
            Id = trade.IdTrade,
            Code = trade.CdTrade,
            Description = trade.DeTrade,
            Comments = trade.DeComentarios,
            TypeId = trade.IdTipoTrade,
            BrokerId = trade.EvgTGBrokerTrade.FirstOrDefault().IdBroker,
            BillingCycleId = trade.IdCicloFacturacion,
            CounterpartId = trade.IdSujeto,
            StartDate = trade.FhIni,
            EndDate = trade.FhFin,
            SignatureDate = trade.FhFirma,
            Positions = trade.EvgTGPosicion.Select(pos => new Position
            {
                Amount = pos.Cantidad,
                Code = pos.CdPosicion,
                Description = pos.DePosicion,
                LogisticElement = pos.IdElemLogNavigation.DeElemLog,
                StartDate = pos.FhIni,
                EndDate = pos.FhFin,
                FormulaId = pos.IdFormula,
                Operations = pos.EvgTGOperacionCv.Select(op =>
                    new Operation()
                    {
                        TypeId = op.IdTipoOperacion,
                        Fee = op.Fee,
                        Date = op.FhOperacionCv,
                        Price = op.NmPrecio ?? 0,
                        Quantity = op.NmCantidadKwh ?? 0,
                    }),
            })
        })
        .FirstOrDefaultAsync();
    return firstOrDefaultAsync;
}

I'm getting an exception at the first line saying

Microsoft.EntityFrameworkCore.Query: Error: An exception occurred while iterating over the results of a query for context type 'SampleApp.EF.MyDbContext'. System.InvalidOperationException: Nullable object must have a value.

I've inspected the exception and the stack trace and it doesn't say anything about which is the problematic object. No clue of what's wrong.

So, is there a method to know which property generates the conflict? I'm sure it's a property-column mismatch, but what if you have a a lot of properties? It's quite painful!

Update

I've already fixed the problem. I was due to an attempt of assigning null to a property in my model that was non-nullable.

That said, this questions isn't about this concrete fix, but about finding a general way to debug this kind of situation (this exception) that are quite common. IMHO, the exception message is too vague. It doesn't provide any useful information of the conflicting property.

1
0
1/22/2020 10:33:16 PM

Accepted Answer

Usually, as far as I know, it doesn't have a quicker way to find what is the exactly field that is making the issue.

What you can do looking at your case, is:

1 - Look the query that you are doing, and verify if it is returning the data needed. If that it is happening well, so probably the query could return null, and your model doesn't accept that (and vice-versa).

2 - If the first item is working properly, try to look at the other iterations that you are doing on the model. For example: you are doing Positions.Select(), so verify if the positions, and the other things coming from the positions model are all fine.

3 - If you are not a hundred per cent sure about what is the field. Just put a nullable type for every field you are doing a linq. Example: BrokerId = trade.EvgTGBrokerTrade.FirstOrDefault().IdBroker, you can add a question mark to make sure that the field is not going to crash your application.

4 - Look at the tables that you create on the database, probably it will have the information of the fields if they are nullable or not. Then, you can alter on your model of the code.

These are the things that I suggest for you

0
1/22/2020 5:05:05 PM

Popular Answer

There can be two answers.

Firstly, this may be probably because your query is returning NULL and the model is not accepting null.

Second fix may be, if you are using anonymous types, then try typecasting the query result into nullable type.

e.g.

Id = (int?) op.Id,

how to find which property is returning NULL?

You can enable SQL Profiler and check the SQL query which is getting executed. Copy the query into SSMS and see which values are NULL.
This may be helpful for you to decide out if you really need nullable typecast OR you want to change the query itself.

There is an issue on GitHub on this page.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow