简体   繁体   中英

Auto increment column .NET

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])
);

您需要在SQL中的模型不仅要说NOT-NULL,还需要在AUTO_INCREMENT之间添加一个空格。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM