【发布时间】:2015-08-24 11:28:38
【问题描述】:
我有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 中注册 Repository:
.....
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 插入到列 'Id'、表 'ln_resources.dbo.KeyProd' 中;列不允许空值。 INSERT 失败。\r\n语句已终止。
我尝试插入的模型具有 id (3)。不为空。我在调试模式下检查过。
我在 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 INSERT 直接从SQL SERVER 插入此模型,则一切正常。
哪里出了问题?为什么 Id 为空?为什么映射不起作用。
【问题讨论】:
-
您能否发布您的
KeyProd课程的简化版本,包括Id字段? -
嗨,迈克 C。当然
标签: c# sql asp.net entity-framework sql-server-2012