DB first Entity Framework 核心在SaveChanges()时抛出这个异常; 此代码适用于 Entity Framework,但不适用于 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), );
最佳答案
我错了 当我第一次创建表时,productNo 是 bigint,我根据该表创建了模型。 在那之后不知何故(一定是我......) productNo 变成了 int。 将 productNo 改回 bigint 后工作正常
关于c# - Entityframework Core 无法将类型为 'System.Int32' 的对象转换为类型 'System.Int64',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42077062/