1

I'm having this weird problem where I try to save the value of an unsigned nullable field into a db using Entity Framework 6 and it always sets the value as NULL in Db even when I send actual values to save. I'm not sure what I'm doing wrong here.

I have entity class:

[Table("Order")]
public class OrderForComparision
{
    [Key]
    public string TicketNumber { get; set; }
    public unint? OriginID { get; set; }
}

I have the table create query that looks like this:

CREATE TABLE [dbo].[Order](
    [TicketNumber] [varchar](50) NOT NULL,
    [OriginID] [bigint] NULL,
 CONSTRAINT [PK_OrderId] PRIMARY KEY CLUSTERED 
(
    [TicketNumber] ASC
))

I update the table this way:

    try
    {
        using (var dbCon = GetDbContext())
        {
            var orderInDb = await dbCon.Orders.FirstOrDefaultAsync(x => x.TicketNumber == order.TicketNumber);
            if (orderInDb == null)
            {
                orderInDb = new OrderForComparision
                {
                    TicketNumber = order.TicketNumber,
                    OriginID = order.OriginID ?? null,
                };
                dbCon.Orders.Add(orderInDb);
            }
            else
            {
                orderInDb.OriginID = order.OriginID ?? null;
            }
            await dbCon.SaveChangesAsync();
        }
    }
    catch (Exception ex)
    {
        throw ex;
    }

I only see NULL in Db even when I pass value to this field. When I check the object while debugging, I see this:

ColumnName  Value   Type
OriginID    3823    uint?

I have tried:

OriginID == null ? (uint?)null : order.OriginID.Value,

OriginID = order.OriginID.HasValue ? order.OriginID.Value : (uint?)null

and

OriginID = order.OriginID ?? null. And nothing has worked for me yet. Could it be the issue with my Db or the way I'm saving? I just can't figure out this simple weird issue.

Ash K
  • 1,802
  • 17
  • 44

1 Answers1

0

You always send null value thats why it is always saving null value.

Change

OriginID?? null

to

OriginID==null??null: OriginID
Syed Md. Kamruzzaman
  • 979
  • 1
  • 12
  • 33
  • No, I'm not always sending null value. And I have already did this: `OriginID == null ? (uint?)null : order.OriginID.Value` which doesn't work. I also tried `OriginID = order.OriginID.HasValue ? order.OriginID.Value : (uint?)null` which is basically the same as `OriginID = order.OriginID ?? null`. And nothing has worked for me yet. – Ash K Apr 03 '20 at 03:06
  • Then check order.OriginID.value==null?? – Syed Md. Kamruzzaman Apr 03 '20 at 03:48
  • EF doesn't support unsigned data types does it? Try changing the model to a long? – Selthien Apr 08 '20 at 03:16