Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entityframework Core Unable to cast object of type 'System.Int32' to type 'System.Int64'

DB first entity framework core throws this exception when SaveChanges(); This code works just fine with Entity Framework but not with Entity Framework Core.

Exception message: Unable to cast object of type 'System.Int32' to type 'System.Int64'.

CsProduct csProduct = new CsProduct()
{
    CheapestPrice = 1,
    LastPrice = 1,
    LastUpdateDate = DateTime.Now,
    ProductName = "123",
    Quantity = 1,
    UploadDate = DateTime.Now
};
CSContext ctx = new CSContext();
ctx.Entry(csProduct).State = EntityState.Added; 
// ctx.CsProduct.Add(csProduct); This does not work neither
csProduct.ProductNo = 0; // Still throws exception without this line
ctx.SaveChanges();  

------------------------------------------------------------------ 
CsProduct.cs
public partial class CsProduct
{
    public CsProduct()
    {
    }

    public long ProductNo { get; set; }
    public string ProductName { get; set; }
    public decimal CheapestPrice { get; set; }
    public decimal LastPrice { get; set; }
    public int Quantity { get; set; }
    public DateTime UploadDate { get; set; }
    public DateTime LastUpdateDate { get; set; }
    public string Comment { get; set; }
}
------------------------------------------------------------------------------
DDL
CREATE TABLE CS_Product(
    productNo               bigint              IDENTITY(1,1)   NOT NULL,
    productName             nvarchar(256)                   NOT NULL,
    cheapestPrice               decimal(14,2)                   NOT NULL,
    lastPrice                   decimal(14,2)                   NOT NULL,
    quantity                    int                         NOT NULL,
    uploadDate              datetime                        NOT NULL,
    lastUpdateDate          datetime                        NOT NULL,
    comment                 nvarchar(450)                           ,
    CONSTRAINT PK_CS_Product PRIMARY KEY (productNo),
);
like image 683
jong shin Avatar asked Oct 19 '25 21:10

jong shin


2 Answers

It was my mistake.. When I first created the table, productNo was bigint and I created the model based on that table. After that somehow (it must be me...) productNo changed to int. It is working just fine after changing productNo back to bigint

like image 195
jong shin Avatar answered Oct 21 '25 11:10

jong shin


Is there a reason behind this line

csProduct.ProductNo = 0;

the framework will assign the key after save.

Just remove that line, If you want the ID then after .SaveChanges(); then check the ID value of the Entity.

csRepository.CSContext.SaveChanges();
var NewID = csProduct.ProductNo;
like image 35
Joe Ricklefs Avatar answered Oct 21 '25 10:10

Joe Ricklefs



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!