7

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; }

    }
Antarr Byrd
  • 24,863
  • 33
  • 100
  • 188
  • 1
    this has nothing to do with MVC. your talking about an `IDENTITY`, which is a database concern. – RPM1984 Aug 24 '11 at 00:43

3 Answers3

11

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

Matt Weldon
  • 1,413
  • 11
  • 18
Eugene Pavlov
  • 688
  • 5
  • 18
8
using System.ComponentModel.DataAnnotations;
public class Category
{


   [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    [Required]
    public int Id { get; set; }
}
njoromwando
  • 91
  • 1
  • 3
5

If you want this to all happen automatically where you don't specify any id and it just 'works' set this field in the database to be an identity field as shown below. column identity in visual studio

If you are using Entity Framework Code First - there is no current support in v4 for this. See: Does Entity Framework 4 Code First have support for identity generators like NHibernate?

If you are using 4.1 and you have an existing database see this link, note the support of existing identity fields:

Using Entity Framework 4.1 Code First with an existing database I'm not sure if this is supported for code first (with no db) yet in 4.1 though.

Community
  • 1
  • 1
Adam Tuliper
  • 29,982
  • 4
  • 53
  • 71