创建另一个实体时添加不存在的实体

发布于 2025-01-04 05:22:23 字数 593 浏览 4 评论 0原文

我正在使用 Asp.net MVC3 和 Entity Framework 4 设置博客。博客文章的大部分属性已经存在于数据库中,因此可以在创建过程中轻松链接到博客文章。

我添加的最后一个元素之一是源,这些源有到我的 BlogPost 的直接链接,并且必须在创建 BlogPost 期间添加。我的想法是使用 BlogPost 实体的实体属性 Sources,例如:

blogPost.Sources.Add(new Source() { Name = source.Value, Url = source.Key.ToString(), Type = "source" });

不幸的是,我不允许以这种方式创建和添加 Source,我收到错误:“无法在表 'Source' 中插入标识列的显式值' 当 IDENTITY_INSERT 设置为 OFF 时。”

我猜这是 ID 列的原因,该列打开了身份增量的身份,但我自己没有设置任何 ID。我尝试使 id = null,但由于它不是可以为 null 的,所以也不允许。 我相信关闭此功能可以让我使用自己的 ID 添加记录,但这不是我想要的。数据库应该创建 ID。

有没有办法在创建过程中添加这些类型的属性?

I'm setting up a blog using Asp.net MVC3 and Entity framework 4. Most of the properties of the blog post already exist in the database, and therefore can easily be linked to the blog post during the creation.

One of the last element I've added are sources, these sources have a direct link to my BlogPost and have to be added during the creation of the BlogPost. My idea was to use the entity property Sources of the BlogPost entity, like:

blogPost.Sources.Add(new Source() { Name = source.Value, Url = source.Key.ToString(), Type = "source" });

Unfortunately I'm not allowed to create and add an Source this way, I'm getting the error: "Cannot insert explicit value for identity column in table 'Source' when IDENTITY_INSERT is set to OFF."

I guess this is cause of the ID column which has is an Identity with Identity increment turned on, but I don't set any ID myself. I tried to make id = null, but since its not a null-able it's not allowed either.
I believe turning this feature off let's me add records with my own ID's, but this is not what I want. The database should create the ID's.

Is there a way to add these kinds of properties during creation?

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

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

发布评论

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

评论(1

撩动你心 2025-01-11 05:22:23

我通过再次从数据库添加源实体解决了这个问题,显然实体框架模型是在字段设置为“身份增加”之前生成的,因此想要插入它自己的 ID。

I solved the problem by adding the Source entity again from the database, apparently the entity framework model was generated before the field was set to Identity Increasing and therefore wanted to insert it's own ID's.

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