开发者

Entity Framework 4.0 insert new object error

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:

  1. Why isn't the designer smart enough to have StoreGeneratedPattern set to Identity by default when it generates the class, assuming开发者_StackOverflow社区 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).

  2. 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).


Try setting the IsIdentity to Yes for the Id column in the Database. I assume that's the problem here, since you mention that EF itself doesn't set StoreGeneratedPattern to Identity.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜