Entity Framework 4.0插入新对象错误
我有一个在 Visual Studio 2010 中使用 Entity Framework 4.0 的项目。我有以下代码:
using (var db = new MyEntities())
{
var dbLead = db.Leads.CreateObject();
dbLead.Email = lead.Email;
db.Leads.AddObject(dbLead);
db.SaveChanges();
}
其中 MyEntities
是通常的 EF 对象上下文。 Lead
是 EF 生成的类,它映射到数据库中相应的表。除了上面代码中分配的 Email
属性之外,Lead
类还有一个 Id
属性,我在这里没有显式设置该属性。所有预期的事情,还没有什么奇怪的。
我在调用 db.SaveChanges()
时遇到异常,指出问题是“重复主键”。但是,在数据库中,我将相应的列标记为主键,并且在 .edmx 设计器中,相应的属性将 EntityKey 标记为 true,将 StoreGeneratePattern 标记为 Identity。
几个问题:
假设基础表将相应的列设置为主键,为什么设计者不够聪明,在生成类时默认将 StoreGeneratePattern 设置为 Identity?就我而言,我必须进入设计器中的每个类,并自己为每个主键属性设置此值(尽管有趣的是,EntityKey 按预期默认设置为 true)。
它仍然不起作用...为什么?我尝试将 StoreGeneratePattern 设置为 Computed,但没有运气(意料之中,否则我会想知道为什么将其设置为 Computed 可以解决问题)。
I have a project using Entity Framework 4.0 in Visual Studio 2010. I have the following code:
using (var db = new MyEntities())
{
var dbLead = db.Leads.CreateObject();
dbLead.Email = lead.Email;
db.Leads.AddObject(dbLead);
db.SaveChanges();
}
where MyEntities
is the usual EF object context. Lead
is an EF-generated class, which maps to a corresponding table in the database. In addition to the Email
property assigned in the code above, the Lead
class has an Id
property, which I am not explicitly setting here. All the expected stuff, nothing strange yet.
I'm getting an exception on the call to db.SaveChanges()
, citing "duplicate primary key" as the problem. However, in the DB, I have the corresponding column marked as a primary key, and in the .edmx designer, the corresponding property is marked with EntityKey as true and StoreGeneratedPattern as Identity.
Couple questions:
Why isn't the designer smart enough to have StoreGeneratedPattern set to Identity by default when it generates the class, assuming the underlying table has the corresponding column set to a primary key? In my case, I had to go into every class in the designer, and set this value myself for every primary key property (though, interestingly, EntityKey is set to true by default, as expected).
It's still not working... Why? I've tried setting the StoreGeneratedPattern to Computed instead, but no luck (expected, otherwise I'd be wondering why setting it to Computed fixed the problem).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
尝试将数据库中
Id
列的IsIdentity
设置为Yes
。我认为这就是这里的问题,因为您提到 EF 本身没有将StoreGeneratePattern
设置为Identity
。Try setting the
IsIdentity
toYes
for theId
column in the Database. I assume that's the problem here, since you mention that EF itself doesn't setStoreGeneratedPattern
toIdentity
.