Entityframework Core无法将“System.Int32”类型的对象强制转换为“System.Int64”类型

时间:2017-02-06 20:51:50

标签: c# sql-server entity-framework-core

DB第一个实体框架核心在SaveChanges()时抛出此异常; 此代码适用于Entity Framework,但不适用于Entity Framework Core。

  

异常消息:无法将类型为“System.Int32”的对象强制转换为“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),
);

2 个答案:

答案 0 :(得分:1)

这是我的错误.. 当我第一次创建表时,productNo是bigint,我根据该表创建了模型。 之后不知何故(一定是我......)productNo改为int。 将产品更改为bigint

后工作正常

答案 1 :(得分:0)

这条线背后有原因

csProduct.ProductNo = 0;

框架将在保存后分配密钥。

只需删除该行,如果你想要ID,那么.SaveChanges(); 然后检查实体的ID值。

csRepository.CSContext.SaveChanges();
var NewID = csProduct.ProductNo;
相关问题