【问题标题】:Entityframework Core Unable to cast object of type 'System.Int32' to type 'System.Int64'Entityframework Core 无法将“System.Int32”类型的对象转换为“System.Int64”类型
【发布时间】: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


【解决方案1】:

这是我的错误.. 当我第一次创建表时,productNo 是 bigint,我基于该表创建了模型。 之后不知何故(一定是我......)productNo更改为int。 将 productNo 改回 bigint 后工作正常

【讨论】:

  • 你拯救了我的一天
  • bigint 和位。有时我们会看到同样的情况。我和你有同样的问题。
【解决方案2】:

这条线背后有原因吗

csProduct.ProductNo = 0;

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

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

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

【讨论】:

  • 把那一行去掉。
  • 仅供参考,该代码适用于实体框架,但不适用于实体框架核心......
  • 不确定存储库中有什么,但通常我附加新实体,然后设置状态,然后保存。
  • 存储库中确实没有任何内容。它现在只返回上下文。我确实尝试过先附加新实体,但它仍然无法正常工作......我真的不明白为什么它适用于实体框架而不适用于实体框架核心。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-06
  • 2013-07-10
  • 2020-08-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多