EntityFramework用值" 00000000-0000-0000-0000-000000000000"填充uniqueidentifier。

时间:2012-06-21 21:29:44

标签: entity-framework uniqueidentifier

在我的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

当我插入记录时,实体framewrok已将TrackingID预先填充为“00000000-0000-0000-0000-000000000000”。我设置字段属性为Computed and Identity没有这样的运气任何想法:这是我的代码片段:

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

3 个答案:

答案 0 :(得分:3)

看起来EF并不认为这个列是一个标识列,所以它的默认设置(Guid)。看看这里有关制作guid标识列的一些细节(它实际上是通过您的确切示例)http://leedumond.com/blog/using-a-guid-as-an-entitykey-in-entity-framework-4/

答案 1 :(得分:0)

在我的情况下(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);
    }
}

答案 2 :(得分:0)

我遇到了同样的问题。以下解决方案为我工作。

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

如果您的EF版本是4,那么您可能只使用设计器时遇到此问题。您可能需要手动编辑StoreGeneratedPattern并在存储模型中设置< Property Name="EmpId" Type="uniqueidentifier" Nullable="false" StoreGeneratedPattern="Identity" />

示例:

JPEG
相关问题