Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Auto Increment Data Type Model

Hello I'm trying to define the CatergoryModel for my MVC3 app. And I would like to know how can I set Id to auto increment.

public class Category
    {
        [Required]
        public int Id { get; set; }

        [Required]
        public string Name { get; set; }

        [Required]
        public string Type { get; set; }

        [Required]
        public string Title { get; set; }

        [Required]
        public string MetaKey { get; set; }

        [Required]
        public string MetaKeyDesc { get; set; }

        [Required]
        public DateTime CreatedAt { get; set; }

        [Required]
        public DateTime UpdatedAt { get; set; }

        public int CategoryId { get; set; }

    }
like image 348
Antarr Byrd Avatar asked Aug 24 '11 00:08

Antarr Byrd


People also ask

Is auto increment a data type?

Auto Increment is a function that operates on numeric data types. It automatically generates sequential numeric values every time that a record is inserted into a table for a field defined as auto increment.

How do you implement auto increment?

The MS SQL Server uses the IDENTITY keyword to perform an auto-increment feature. In the example above, the starting value for IDENTITY is 1, and it will increment by 1 for each new record. Tip: To specify that the "Personid" column should start at value 10 and increment by 5, change it to IDENTITY(10,5) .

Can you auto increment varchar in MySQL?

AutoIncrement fields are integer in mysql. You can mirror the auto-increment field in a varchar field and create a trigger which updates the varchar field on insert/update.

How does auto increment work in SQL?

The auto increment in SQL is a feature that is applied to a field so that it can automatically generate and provide a unique value to every record that you enter into an SQL table. This field is often used as the PRIMARY KEY column, where you need to provide a unique value for every record you add.


2 Answers

Simply put a [Key] annotation before the Id field.

like image 124
Eugene Pavlov Avatar answered Sep 19 '22 19:09

Eugene Pavlov


using System.ComponentModel.DataAnnotations;
public class Category
{


   [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    [Required]
    public int Id { get; set; }
}
like image 33
njoromwando Avatar answered Sep 17 '22 19:09

njoromwando