实体框架:在 SaveChanges 期间在代码中设置实体 id 时抱怨 null id

发布于 2024-10-13 06:39:07 字数 1745 浏览 0 评论 0原文

让我们假设以下代码处理 DataContext 的 SaveChanges 事件

void Context_SavingChanges(object sender, EventArgs e)
    {

        IEnumerable<ObjectStateEntry> objectStateEntries =
            from ose in this.ObjectStateManager.GetObjectStateEntries(EntityState.Added | EntityState.Modified | EntityState.Deleted)
            where ose.Entity != null
            select ose;

        foreach (ObjectStateEntry entry in objectStateEntries)
        {
            foreach (var field in entry.CurrentValues.DataRecordInfo.FieldMetadata)
            {
                var guid = Guid.NewGuid();
                AuditEntry audit = AuditEntry.CreateAuditEntry(
                    id: guid,
                    entitySet: entry.EntitySet.Name,
                    typeName: entry.Entity.GetType().Name,
                    entityId: (entry.CurrentValues["Id"] as string) ?? ((entry.State == EntityState.Added) ? "New" : null),
                    oldValue: (entry.State != EntityState.Added) ? entry.OriginalValues[field.FieldType.Name].ToString() : "New",
                    newValue: (entry.State != EntityState.Deleted) ? entry.CurrentValues[field.FieldType.Name].ToString() : "Deleted",
                    modifier: Environment.UserDomainName + "\\" + Environment.UserName,
                    dbAction: Enum.GetName(typeof(EntityState), entry.State),
                    field: field.FieldType.Name,
                    dateStamp: DateTime.Now
                );


                this.AuditEntries.AddObject(audit);
            }
        }
    }

当我创建一个新实体并尝试保存它的更改时,我收到此错误:

无法将 NULL 值插入表“TimeEF.dbo.AuditEntries”的“Id”列;列不允许为空。插入失败。 该声明已终止。

正如你所看到的,我已经设置了 Id,有什么想法吗?漏洞?

Lets assume the following code handling the SaveChanges event of a DataContext

void Context_SavingChanges(object sender, EventArgs e)
    {

        IEnumerable<ObjectStateEntry> objectStateEntries =
            from ose in this.ObjectStateManager.GetObjectStateEntries(EntityState.Added | EntityState.Modified | EntityState.Deleted)
            where ose.Entity != null
            select ose;

        foreach (ObjectStateEntry entry in objectStateEntries)
        {
            foreach (var field in entry.CurrentValues.DataRecordInfo.FieldMetadata)
            {
                var guid = Guid.NewGuid();
                AuditEntry audit = AuditEntry.CreateAuditEntry(
                    id: guid,
                    entitySet: entry.EntitySet.Name,
                    typeName: entry.Entity.GetType().Name,
                    entityId: (entry.CurrentValues["Id"] as string) ?? ((entry.State == EntityState.Added) ? "New" : null),
                    oldValue: (entry.State != EntityState.Added) ? entry.OriginalValues[field.FieldType.Name].ToString() : "New",
                    newValue: (entry.State != EntityState.Deleted) ? entry.CurrentValues[field.FieldType.Name].ToString() : "Deleted",
                    modifier: Environment.UserDomainName + "\\" + Environment.UserName,
                    dbAction: Enum.GetName(typeof(EntityState), entry.State),
                    field: field.FieldType.Name,
                    dateStamp: DateTime.Now
                );


                this.AuditEntries.AddObject(audit);
            }
        }
    }

When I create a new Entity and attempt to save it's changes I get this error:

Cannot insert the value NULL into column 'Id', table 'TimeEF.dbo.AuditEntries'; column does not allow nulls. INSERT fails.
The statement has been terminated.

When as you can see I have set the Id, any ideas? Bug?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

久隐师 2024-10-20 06:39:07

您是否检查过 EDMX 文件中对象的 id 列?如果其 StoreGeneratePattern 属性标记为“计算”或“身份”,则 EF 不会将 C# 值传递到其 SQL 语句。将 StoreGeneratePattern 属性设置为“None”,实体框架编写的 SQL 将包含 C# 创建的 id 值。

<EntityType Name="AuditEntry">
    //...
    <Property Name="id" Type="int" Nullable="false" StoreGeneratedPattern="None" />
    //...
</EntityType>

有关详细信息,请参阅 http://msdn.microsoft.com/en- us/library/dd296755(v=vs.90).aspx

Have you examined the id column of your object in the EDMX file? If its StoreGeneratedPattern attribute is marked as "computed" or "identity", then EF will not carry the C# value over to its SQL statement. Set the StoreGeneratedPattern attribute to "None" and the SQL that Entity Framework writes will contain your C#-created value for id.

<EntityType Name="AuditEntry">
    //...
    <Property Name="id" Type="int" Nullable="false" StoreGeneratedPattern="None" />
    //...
</EntityType>

For more information, see http://msdn.microsoft.com/en-us/library/dd296755(v=vs.90).aspx.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文