c# - Entityframework Core 无法将类型为 'System.Int32' 的对象转换为类型 'System.Int64'

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

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/

相关文章:

c# - .NET 中获取从 0 到 n 的 int 数组的方法

c# - 我如何从 live.com 获取 OAuth request_token?

c# - ConcurrentDictionary - 将 addValueFactory (Func<string, T, T> ) 转换为 updateValueFactory (Func<string, T, T>)?

sql-server - Sql Server 2008 的更改通知

sqlite - 创建表 Entity Framework Core 和 SQLite

c# - 无法在对象中插入重复的键 - 如何在 Entity Framework Core 中创建复合键

c# - 是否可以自定义 ViewState 实现?

sql - select unique * 查询有多贵

sql-server - 关于不同值和大型结果集以及用于审计的单个垂直表的聚集索引考虑

c# - Entity Framework Core 的 MySQL 排序规则问题