Entity Framework making nullable unsigned int field's value as null while saving into database

.net c# dbcontext entity-framework-6 nullable

Question

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.

1
0
4/3/2020 12:53:24 PM

Popular Answer

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

Change

OriginID?? null

to

OriginID==null??null: OriginID
0
4/3/2020 4:02:13 AM


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