【问题标题】:EntityFramework populating uniqueidentifier with value "00000000-0000-0000-0000-000000000000"EntityFramework 填充值为“00000000-0000-0000-0000-000000000000”的唯一标识符
【发布时间】:2012-06-21 21:29:44
【问题描述】:

在我的 WCF 服务中,我使用的是 Entity Framework .NET 4.0, 在我的数据库中,我有这张表:

CREATE TABLE [dbo].[Tracking](
    [TrackingID] [uniqueidentifier] ROWGUIDCOL  NOT NULL,   
    ...
 CONSTRAINT [PK_Tracking] PRIMARY KEY CLUSTERED 
(
    [TrackingID] ASC
)
) ON [DATA]
ALTER TABLE [dbo].[Tracking] ADD  CONSTRAINT [DF_Tracking_TrackingID]  DEFAULT (newid()) FOR [TrackingID]
GO

当我插入记录时,Entity framewrok 已将 TrackingID 预填充为“00000000-0000-0000-0000-000000000000”。我已将字段属性设置为 Computed 和 Identity,但没有任何想法:这是我的代码 sn-p:

using (var context = new DB.PTLEntities())
{
     var tracking = new DB.Tracking();       
     context.Trackings.AddObject(tracking);
     context.SaveChanges();
     trackingID = tracking.TrackingID;
}

【问题讨论】:

    标签: entity-framework uniqueidentifier


    【解决方案1】:

    看起来 EF 不认为此列是标识列,因此它使用默认值(Guid)。在此处查看有关使 guid 成为身份列的一些详细信息(它实际上通过您的确切示例)http://leedumond.com/blog/using-a-guid-as-an-entitykey-in-entity-framework-4/

    【讨论】:

    • @oxfn 尝试回程机器:web.archive.org/web/20120215161924/http://leedumond.com/blog/… 很遗憾他的博客离线,我可能会在某个阶段将其中的一些内容纳入我的答案
    • 我现在看到,这不是 EF 问题,而是 Visual Studio EDMX 生成器的问题。它没有为uniqueidentifier 列设置StoreGeneratedPttern="Identity" 属性,即使它们有DEFAULT NEWID(),所以你必须手动设置它
    【解决方案2】:

    我遇到了同样的问题。以下解决方案对我有用。

    需要在 EF 设计器中更改属性的 StoreGeneratedPattern 值。将其设置为Identity。这将导致 EF 避免在插入上设置值,然后在插入完成后捕获它。

    如果您的 EF 版本是 4,那么仅使用设计器可能会遇到问题。您可能需要手动编辑.edmx 并在存储模型本身中设置StoreGeneratedPattern

    例子:

    < Property Name="EmpId" Type="uniqueidentifier" Nullable="false" StoreGeneratedPattern="Identity" />
    

    【讨论】:

      【解决方案3】:

      在我的情况下(EF >= 4.1)我需要为表本身添加一个默认值:

      ALTER TABLE MyTable ADD  DEFAULT (newid()) FOR [Id]
      

      此外,如果您使用自己的上下文,您应该告诉 EF 该列是标识列:

      public class ShedContext : DbContext
      {
          protected override void OnModelCreating(DbModelBuilder modelBuilder)
          {
              modelBuilder.Entity<DraftFromWebOneOff>()
                  .Property(d => d.Id)
                  .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
      
              base.OnModelCreating(modelBuilder);
          }
      }
      

      【讨论】:

      • 你的答案是关于 EF >= 4.1
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-07
      • 1970-01-01
      • 2011-10-23
      • 1970-01-01
      相关资源
      最近更新 更多