【问题标题】:using Guid as PK with EF4 Code First使用 Guid 作为 PK 和 EF4 Code First
【发布时间】:2011-07-13 08:18:05
【问题描述】:

我有这个班级和桌子:

public class Foo
{
public Guid Id {get;set;}
public string Name {get;set;}   
}

create table Foo
(
id uniqueidentifier primary KEY DEFAULT (newsequentialid()),
name nvarchar(255)
)

问题是当我尝试保存新的 foo 时,第一个与 0000-000-00 ... id 一起使用,第二个也是,所以我得到约束异常

有人知道解决办法吗?

【问题讨论】:

    标签: entity-framework-4 code-first entity-framework-ctp5 ef4-code-only


    【解决方案1】:

    您是否设置了 Identity StoreGeneratedPattern?
    您可以在OnModelCreating 方法中做到这一点:

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

    或使用 DataAnnotation 属性:

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

    【讨论】:

      【解决方案2】:

      基于 Devart 的解决方案,我遇到了这个问题并使用了

      [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
      

      数据注释不起作用。这样做的原因是我正在使用(如代码优先教程之一中所建议的)一个不支持将 Guid 作为身份的 SqlServerCompact 数据库。只是想我会在这里发帖,以防其他人遇到这个问题。如果您更改连接字符串以创建 SqlServer mdf 而不是 Compact 数据库,则它可以完美运行。

      【讨论】:

      • 您使用的是哪个版本的 Compact Edition 和 EF? CE 4.0 和 EF 6 似乎没问题。这在 CE 的后续版本中解决了吗?
      • @mack 它可能已经解决了,我的帖子是几年前的:)
      • @Manatherin 我现在在带有 EF 6.1.0 的 VS2013 Update 2 中遇到了这个问题。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多