我有一個C#.NET的Web應用程序,我想創建一個ID的自動增量。我無法弄清楚我做錯了什麼,但是我不斷收到錯誤,因爲它沒有增加。自動增量列.NET
錯誤:
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.
控制器:
[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);
}
型號:
[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; }
模型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>
模型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])
);
該列在SQL中看起來像什麼?它是否具有身份規範? – jrummell
你用什麼來生成你的數據庫? Code First EF? –
@jrummell我在你的請求中加入了sql模型 –