2017-02-06 66 views
1

DB第一个实体框架核心在SaveChanges(); 此代码适用于实体框架,但不适用于实体框架核心。Entityframework Core无法将类型为'System.Int32'的对象强制类型为'System.Int64'

异常消息:无法将类型为“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), 
); 
+0

是否有任何流利的映射代码或错误地将类型设置为'Int32'的迁移代码? – Igor

+0

EF Core版本:1.1.0,它应该正确映射主键。因为它是由实体框架使用Scaffold-DbContext生成的 –

回答

1

这是我的错.. 当我第一次创建表,productNo是BIGINT和我创建基于该表的模型。 之后,以某种方式(它一定是我...)productNo更改为int。 更改productNo后工作正常没有回bigint

0

是否有这条线

csProduct.ProductNo = 0; 

框架将分配键保存后,后面的原因。

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

csRepository.CSContext.SaveChanges(); 
var NewID = csProduct.ProductNo; 
+0

只是将该行留出。 –

+0

我已经尝试过了,但是我收到了同样的异常。 –

+0

仅供参考,该代码适用于实体框架,但不适用于实体框架核心... –

相关问题