开发者

How to Auto Increment Data Type Model

Hello I'm trying to defin开发者_如何转开发e 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; }

    }


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


using System.ComponentModel.DataAnnotations;
public class Category
{


   [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    [Required]
    public int Id { get; set; }
}


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.

How to Auto Increment Data Type Model

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜