Reputation: 349
I have an C# .NET web application and I want to create an auto increment on an id. I can't figure out what I'm doing wrong but I keep getting errors because it doesn't increase.
Error:
Cannot insert the value NULL into column 'Id', table 'Samen de Zorg.dbo.BulletinItem'; column does not allow nulls. INSERT fails.
The statement has been terminated.
Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "UserID,Title,Description")] BulletinItem bulletinItem)
{
//
if (ModelState.IsValid)
{
db.BulletinItem.Add(bulletinItem);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(bulletinItem);
}
Model:
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string UserID { get; set; }
public string Title { get; set; }
public string Description { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<BulletinReaction> BulletinReaction { get; set; }
Model in XML:
<EntityType Name="BulletinItem">
<Key>
<PropertyRef Name="Id" />
</Key>
<Property Name="Id" Type="int" Nullable="false" StoreGeneratedPattern="Identity" />
<Property Name="UserID" Type="nvarchar" MaxLength="256" Nullable="false" />
<Property Name="Title" Type="nvarchar" MaxLength="50" Nullable="false" />
<Property Name="Description" Type="nvarchar(max)" Nullable="false" />
</EntityType>
Model in SQL:
CREATE TABLE [dbo].[BulletinItem]
(
[Id] INT NOT NULL,
[UserID] NVARCHAR (256) NOT NULL,
[Title] NVARCHAR (50) NOT NULL,
[Description] NVARCHAR (MAX) NOT NULL,
CONSTRAINT [PK_BulletinItem]
PRIMARY KEY CLUSTERED ([Id] ASC),
CONSTRAINT [FK_BulletinItem_AspNetUsers]
FOREIGN KEY ([UserID]) REFERENCES [dbo].[AspNetUsers] ([UserName])
);
Upvotes: 0
Views: 1447
Reputation: 1016
You need your model in SQL to not only say NOT-NULL but also AUTO_INCREMENT just add a space inbetween.
Upvotes: 1