ASP.NET MVC 5,实体框架db.savechanges()返回错误的插入ID

问题描述 投票:0回答:1

我正在使用EF和ASP.NET MVC 5,以及使用时插入数据库

dbcontext.SaveChanges(mymodel)

返回的id始终为“1”,但是在SQL数据库中,插入记录的id为“3”(在插入之前我删除了数据库表中的前两个记录以清除表)。

谁能告诉我如何解决这个问题?我觉得EF没有更新到日期与数据库或缺少任何同步设置?提前谢谢了...

我的代码如下......

if (ModelState.IsValid)
{
    stodoc.StockOutDocument_Serial = srlnum;
    stodoc.StockOutDocument_date = inview.InventoryDate;

    db.StockOutDocuments.Add(stodoc);
    int stodocid = db.SaveChanges(); 
}
entity-framework asp.net-mvc-5
1个回答
2
投票

新创建的记录的ID不是来自SaveChanges调用。 SaveChanges将更新所有修改/插入/删除的记录。

如果您已将实体配置为识别它的ID为DatabaseGeneratedOption.Identity,则获取新插入的ID:

            stodoc.StockOutDocument_Serial = srlnum;
            stodoc.StockOutDocument_date = inview.InventoryDate;
            db.StockOutDocuments.Add(stodoc);
            db.SaveChanges(); 
            int stodocid = stodoc.stodocid; // Will be populated once SaveChanges is called.

如果未更新stodoc.stodocid属性,请检查您是否已在映射中将其配置为标识列:

如果您在实体中使用了属性:

[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int stodocid { get; set; }

或通过实体配置:EF Core:

builder.HasKey(x => x.stodocid);
builder.Property(x => x.stodocid).UseSqlServerIdentityColumn();

EF6:

HasKey(x => x.stodocid)
    .Property(x => x.stodocid)
    .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
© www.soinside.com 2019 - 2024. All rights reserved.