SQL映射问题

时间:2015-06-09 14:50:26

标签: c# sql asp.net entity-framework sql-server-2012

我有CustomDBContext

public class CustomDBContext : DbContext
    {
        public CustomDBContext(string connectionString)
            : base(connectionString)
        {
        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

            ......
            modelBuilder.Entity<KeyProd>().ToTable("KeyProd");
            ......
        }
    }

在Startup.cs中注册存储库:

.....
var builder = new ContainerBuilder();
builder.Register(c => RepositoryFactory.GetInstance<KeyProd, long>("ef")).As<IRepository<KeyProd, long>>().InstancePerRequest();

将此存储库注入我的服务后,我尝试向数据库添加新行:

_keyProductionRepository.Add(new KeyProd
                        {
                            Id = key.Id,
                            Comment = key.Comment,
                            CreatedBy = adminId,
                            DateCreated = DateTime.UtcNow,
                            KeyType = key.KeyType,
                            PageId = key.PageId,
                            Name = key.Name
                        });

例外是: 无法将值NULL插入列&#39; Id&#39;,table&#39; ln_resources.dbo.KeyProd&#39 ;;列不允许空值。 INSERT失败。\ r \ n语句已终止。

我尝试插入的模型有id(3)。不是null。我在调试模式下检查了它。

我在SQl中没有自动增量ID的表。这是表格的查询:

CREATE TABLE [dbo].[KeyProd](
    [Id] [bigint] NOT NULL,
    [Name] [nvarchar](100) NULL,
    [KeyType] [int] NOT NULL,
    [Comment] [text] NULL,
    [PageId] [int] NOT NULL,
    [CreatedBy] [int] NOT NULL,
    [DateCreated] [datetime] NOT NULL DEFAULT (getdate()),
    [DateUpdated] [datetime] NULL DEFAULT (getdate()),
    [UpdatedBy] [int] NULL,
PRIMARY KEY CLUSTERED 
(
    [Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON)
)

GO

ALTER TABLE [dbo].[KeyProd]  WITH CHECK ADD  CONSTRAINT [FK_KeyProd_Page] FOREIGN KEY([PageId])
REFERENCES [dbo].[Page] ([Id])
GO

ALTER TABLE [dbo].[KeyProd] CHECK CONSTRAINT [FK_KeyProd_Page]
GO

我的KeyProd班级:

  public class KeyProd
    {
        public long Id { get; set; }
        public string Name { get; set; }
        public KeyType KeyType { get; set; }
        public string Comment { get; set; }
        public int PageId { get; set; }
        public int CreatedBy { get; set; }
        public DateTime DateCreated { get; set; }
        public int? UpdatedBy { get; set; }
        public DateTime? DateUpdated { get; set; }
    }

如果我尝试使用SQL SERVER直接从SQL INSERT插入此模型,则一切正常。 哪里有问题?为什么Id是空的?为什么映射不起作用。

1 个答案:

答案 0 :(得分:0)

您可能需要在KeyProd上注明关键字段,以表明您不希望您的上下文自动生成该值。尝试将DatabaseGeneratedOption.None添加到您的密钥属性。

public class KeyProd {

    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public long Id { get; set; }

    // ... Other properties
}