将列映射为数据库中的 IDENTITY
尽管我已使用 .Identity()
标记了 ID 列,但生成的数据库架构并未将 IDENTITY
设置为 true,这在添加记录时给我带来了问题。如果我手动编辑数据库架构(在 SQL Management Studio 中)以将 Id
列标记为 IDENTITY
,则一切都会按我想要的方式工作 - 我只是无法让 EF 执行此操作就其本身而言。
这是我的完整映射:
public class EntryConfiguration : EntityConfiguration<Entry>
{
public EntryConfiguration()
{
Property(e => e.Id).IsIdentity();
Property(e => e.Amount);
Property(e => e.Description).IsRequired();
Property(e => e.TransactionDate);
Relationship(e => (ICollection<Tag>)e.Tags).FromProperty(t => t.Entries);
}
}
当我使用 EF 构建和重新构建数据库以进行集成测试时,我确实需要自动完成此操作...
编辑: 嗯...在评论中,我被要求提供足够的代码来执行此操作,因此我将代码剪切并粘贴到控制台应用程序中(这样您就不需要我的所有类...),突然间它就起作用了。我想我忘记了某个地方的一些方法调用,尽管我无法弄清楚在哪里。
我将在这篇文章的答案中发布工作解决方案代码,以防其他人来寻找它。
Although I have marked my ID column with .Identity()
, the generated database schema doesn't have IDENTITY
set to true, which gives me problems when I'm adding records. If I manually edit the database schema (in SQL Management Studio) to have the Id
column marked IDENTITY
, everything works as I want it - I just can't make EF do that by itself.
This is my complete mapping:
public class EntryConfiguration : EntityConfiguration<Entry>
{
public EntryConfiguration()
{
Property(e => e.Id).IsIdentity();
Property(e => e.Amount);
Property(e => e.Description).IsRequired();
Property(e => e.TransactionDate);
Relationship(e => (ICollection<Tag>)e.Tags).FromProperty(t => t.Entries);
}
}
As I'm using EF to build and re-build the database for integration testing, I really need this to be done automatically...
EDIT:
Hm... In a comment I was requested to give enough code to execute this, so I cut-and-pasted my code into a console app (so you wouldn't need all my classes...) and suddenly it just worked. I guess I was forgetting some method call somewhere, although I haven't been able to figure out where.
I'll post the working solution code in an answer to this post, in case someone else comes looking for it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
运行这段代码可以解决这个问题。我想我一定是忘记了某个步骤,所以如果你遇到同样的问题,请确保你做了所有这些事情:
Running this code solves the problem. I guess I must have forgot a step somewhere, so if you have the same problem, make sure you do all these things: