实体框架 - 为类型的非可空成员“RowVersion”返回了一个空存储生成的值

时间:2013-03-25 14:26:17

标签: entity-framework entity-framework-4

我有以下SQL来创建表:

    public const string dropCreate =
        SET ANSI_NULLS ON
        SET QUOTED_IDENTIFIER ON
        IF EXISTS (SELECT name FROM sys.objects WHERE name = 'Application' AND type = 'U')
            DROP TABLE [dbo].[Application]
        CREATE TABLE [dbo].[Application] (
            [ApplicationId] INT IDENTITY (1, 1) NOT NULL,
            [Name] NVARCHAR (50) Not NULL,
            [RowVersion] [varbinary](max) NULL,
            [ModifiedDate] [datetime] NOT NULL,
            CONSTRAINT [PK_dbo.Application] PRIMARY KEY CLUSTERED ([ApplicationId] ASC)
        )";

这是我的班级:

public partial class Application
{
    public Application()
    {
        this.TestAccounts = new List<TestAccount>();
    }

    public int ApplicationId { get; set; }
    public string Name { get; set; }
    public byte[] RowVersion { get; set; }
    public System.DateTime ModifiedDate { get; set; }
    public virtual ICollection<TestAccount> TestAccounts { get; set; }
}

映射:

    public ApplicationMap()
    {
        // Primary Key
        this.HasKey(t => t.ApplicationId);

        // Properties
        this.Property(t => t.Name)
            .IsRequired()
            .HasMaxLength(35);

        this.Property(t => t.RowVersion)
            .IsRequired()
            .IsFixedLength()
            .HasMaxLength(8)
            .IsRowVersion();

        // Table & Column Mappings
        this.ToTable("Application");
        this.Property(t => t.ApplicationId).HasColumnName("ApplicationId");
        this.Property(t => t.Name).HasColumnName("Name");
        this.Property(t => t.RowVersion).HasColumnName("RowVersion");
        this.Property(t => t.ModifiedDate).HasColumnName("ModifiedDate");
    }

我按如下方式插入:

       new TestAccount 
       { 
           Application = app ,
           Name = applicationName, 
           ModifiedDate = DateTime.Now 
       };

它给了我以下异常

InnerException:System.Data.Entity.Infrastructure.DbUpdateException        的HResult = -2146233087        Message =为类型为“Relational.Mappings.Contexts.Application”的非可空成员“RowVersion”返回了null存储生成的值。        源=的EntityFramework

有人可以给我一些建议。据我所知,我已经正确设置了一切。

2 个答案:

答案 0 :(得分:0)

看起来像你的映射:

 this.Property(t => t.RowVersion)
        **.IsRequired()**
        .IsFixedLength()
        .HasMaxLength(8)
        .IsRowVersion();

与您的表格不同:

[RowVersion] [varbinary](max) NULL,

他们需要保持一致。

您是否尝试按http://msdn.microsoft.com/en-us/library/ms182776.aspx设置行版本列?

答案 1 :(得分:0)

将RowVersion更改为TimeStamp