我正在使用实体框架并连接到 MySQL 数据库。id 列设置为使用 StoreGeneratedPattern Identity,并且数据库中的列已设置为自动增量。当我创建一个新对象并将其保存到数据库时,该项目在数据库中正确发布。但是,保存后,C# 中对象的 id 保持为 0,而不是反映数据库分配的值。
部分代码如下:
Group newGroup = new Group("MyGroupName", "Active");
dbContext.Groups.Add(newGroup);
dbContext.SaveChanges();
int testId = newGroup.id;
即使“newGroup”使用数据库分配的 id 保存在数据库中,但当我读取 id 时(例如读取 testId 时),id 仍然为 0。
基于此,我尝试添加
dbContext.Entry(newGroup).Reload();
在 SaveChanges() 之后,我也尝试过(基于this和this)添加
var objectContext = ((IObjectContextAdapter)dbContext).ObjectContext;
objectContext.Refresh(System.Data.Objects.RefreshMode.StoreWins, newGroup);
在 SaveChanges() 之后试图从数据库中刷新对象(以及因此的 id),但问题仍然存在。如何获取数据库分配的 id?
编辑:为组添加类定义:
[Table("groups")]
public partial class Group
{
public Group()
{
this.user_groups = new HashSet<UserGroup>();
}
public long id { get; set; }
public string name { get; set; }
public string status { get; set; }
public System.DateTime created_at { get; set; }
public System.DateTime updated_at { get; set; }
public virtual ICollection<UserGroup> user_groups { get; set; }
}