I have 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");
......
}
}
And Repository registration in Startup.cs:
.....
var builder = new ContainerBuilder();
builder.Register(c => RepositoryFactory.GetInstance<KeyProd, long>("ef")).As<IRepository<KeyProd, long>>().InstancePerRequest();
After injection of this repository to my service, i try to add new row to database:
_keyProductionRepository.Add(new KeyProd
{
Id = key.Id,
Comment = key.Comment,
CreatedBy = adminId,
DateCreated = DateTime.UtcNow,
KeyType = key.KeyType,
PageId = key.PageId,
Name = key.Name
});
The exception is: Cannot insert the value NULL into column 'Id', table 'ln_resources.dbo.KeyProd'; column does not allow nulls. INSERT fails.\r\nThe statement has been terminated.
The model i try to insert have id (3). Is not null.I checked it in debug mode.
My table in SQl without autoincremented Id. This is a query of table:
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
My KeyProd
Class:
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; }
}
If i try to insert this model directly from SQL SERVER
by using SQL INSERT
, all works fine.
Where the problem? Why Id is Null? Why mapping not working.
You may need to annotate the key field on
KeyProd
to indicate that you don't want the value to be automatically generated by your context. Try addingDatabaseGeneratedOption.None
to your key property.