using Guid as PK with EF4 Code First

末鹿安然 提交于 2019-11-28 17:27:04
Devart

Have you set Identity StoreGeneratedPattern?
You can do it in the OnModelCreating method:

modelBuilder.Entity<Foo>().Property(o => o.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);

or using the DataAnnotation attributes:

public class Foo {
  [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
  public Guid Id {get;set;}
  public string Name {get;set;}
}

Just building on Devart's Solution, I had this issue and using the

[DatabaseGenerated(DatabaseGeneratedOption.Identity)]

data annotation didn't work. The reason for this was i was using (as suggested in one of the code first tutorials) a SqlServerCompact database which doesn't support the Guid as identity. Just thought I'd post here in case anyone else had this issue. If you change the connection string so it is creating a SqlServer mdf instead of a Compact database it works perfectly.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!