EF简单插入

时间:2011-08-18 10:48:14

标签: entity-framework c#-4.0 entity

这是最奇怪的事情......也许我有一个金发碧眼的时刻或其他什么,但为什么这不起作用......

FLMCommsEntities dal = new FLMCommsEntities();
foreach (Email email in mail)
{
    dal.EmailReceiveds.AddObject(new EmailReceived
    {
        FromAddress = email.From,
        ToAddress = email.To,
        EmailSubject = email.Subject,
        EmailBodyHtml = email.BodyHtml,
        EmailBodyPlain = email.BodyPlain,
        ReceivedOn = (DateTime)email.Date,
        AttachmentPath = email.AttachmentPath,
        EmailSize = email.Size,
        CreatedDate = DateTime.Now,
        DownloadComplete = true,
        ServerEmailID = email.ServerId
    });
}
// ask dal to save the new mail batch locally
dal.SaveChanges();

它返回一个sql异常,说我无法插入重复的主键值...显然我并没有尝试插入主键值,而是创建一个新键值!

GRRR ......

1 个答案:

答案 0 :(得分:0)

原来我是一个笨蛋并且忘了在数据库中的PK字段上设置“Identity Specifiction”,因此EF不知道它是自动填充了来自SQL Server的生成ID。

没关系......

最后到达那里:)