Entity Framework Core 无法将类型为 'System.Int32' 的对象转换为类型 'System.Int64'。

4

使用 DB first entity framework core 调用 SaveChanges() 时,会抛出以下异常:

异常信息:无法将类型为“System.Int32”的对象强制转换为类型“System.Int64”。

这段代码在 Entity Framework 中可以正常运行,但在 Entity Framework Core 中不行。

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, 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) , 约束 PK_CS_Product 主键 (productNo), );

是否有任何流畅的映射代码或迁移代码会将类型错误地设置为 Int32 - Igor
EF Core版本:1.1.0,应该正确映射主键。因为它是由使用Scaffold-DbContext的实体框架生成的。 - jong shin
2个回答

7

这是我的失误... 当我第一次创建表格时,productNo 是 bigint 类型,并根据该表格创建了模型。 之后不知道为什么(可能是我...),productNo 变成了 int 类型。 将 productNo 改回 bigint 后,它正常工作。


1
你救了我的一天。 - Abdu Imam
大整数和位元。有时我们会看到相同的东西。我和你有同样的问题。 - ToanTV

1
这行代码后面是否有特别的原因?
csProduct.ProductNo = 0;

框架将在保存后分配键。

只需删除该行,如果您想要ID,则在.SaveChanges()之后检查实体的ID值。

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

just leave that line out. - Joe Ricklefs
请注意,该代码在实体框架中可以正常工作,但在实体框架核心中无法正常工作... - jong shin
不确定您的存储库中有什么,但通常我会附加新实体,然后设置状态,最后保存。 - Joe Ricklefs
仓库里真的什么都没有。现在它只是返回上下文。我尝试先附加新实体,但仍然不起作用……我真的无法理解为什么 Entity Framework 可以工作,但 Entity Framework Core 不行。 - jong shin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接