简体   繁体   中英

Identity auto increment not applied on column

After the DB Migration when the tables were created in the Database, the Identity Auto-increment was not applied to the 'Id' Column whereas the Primary Key constraint was applied to it.
Following is the Model class code.

public class Subscription
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public string Id { get; set; }
    public string domainName { get; set; }
    public string articleID { get; set; }
    public string tld { get; set; }
    public string customerID { get; set; }
    public string customerName { get; set; }
    public string price { get; set; }
    public string nextBillDate { get; set; }

}

And following are the columns from the Table that was generated.

在此处输入图片说明

Can someone please help me with how to cleanly apply auto increment in 'Id' Column. I want it to have both the Primary key and the auto increment.

Edit: I changed the type of Id to int but still the auto-increment is not applied to it .Here's a screenshot.

在此处输入图片说明

它的类型应该是int以使其成为 Identity:

public int Id { get; set; }

OK, after you change your Id from string to int and the problem still occurs, I recommend that you should delete your database(if you don't care about data) and delete your Migration file from Visual Studio as well. It is important for you to delete your migration file from program because sometimes it doesn't recognized all changes. Or, you can add this line of code by hand in your migration file(maybe not recommended, but if nothing helps, this will help):

identity: true

So, it should look something like this:

CreateTable("dbo.Table",
            c => new
            {
                Id= c.Int(nullable: false, identity: true),
                ...
            })
            .PrimaryKey(t => t.Id)
            ...

If you have anything like this,

private int _id = -1; 
public int Id {get => _name; set => _name = value};

Just remove it and try this,

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

This solved my problem

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