Reputation: 794
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), );
Upvotes: 4
Views: 31875
Reputation: 794
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
Upvotes: 7
Reputation: 660
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;
Upvotes: 1