【发布时间】:2017-06-23 22:37:04
【问题描述】:
当 SaveChanges(); 时 DB first entity framework core 抛出这个异常; 此代码适用于 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
创建表 CS_Product(
productNo bigint IDENTITY(1,1) NOT NULL,
产品名称 nvarchar(256) 非空,
最便宜的价格小数(14,2)不为空,
lastPrice decimal(14,2) NOT NULL,
数量 int NOT NULL,
uploadDate datetime NOT NULL,
lastUpdateDate 日期时间 NOT NULL,
评论 nvarchar(450) ,
CONSTRAINT PK_CS_Product PRIMARY KEY (productNo),
);
【问题讨论】:
-
是否有流畅的映射代码或迁移代码错误地将类型设置为
Int32? -
EF Core 版本:1.1.0 并且应该正确映射主键..因为它是由实体框架使用 Scaffold-DbContext 生成的
标签: c# sql-server entity-framework-core