简体   繁体   中英

Can I get a primary key to auto-increment in Entity Framework, while having other key

I'm working on a MVC project with Entity Framework and VS 2015.

It has worked so far. Now I've made a relation table-entity to link between two tables, and I can't get the Key-column to auto-increment. It was because I didn't want to remove some constraints in the existing tables that I chose to make a separate entity.

It looks like this:

public class UserCustomer
{

    [Key]
    public int UserCustomerID { get; set; }
    [Index("IX_UserAndCustomer", 1, IsUnique = true)]
    public int UserID { get; set; }
    [Index("IX_UserAndCustomer", 2, IsUnique = true)]
    public int CustomerID { get; set; }

    public DateTime CreatedDate { get; set; }

    public UserCustomer()
    {
        CreatedDate = DateTime.Now;
    }

}

The key column doesn't become auto-incremented.

I've tried Fluent API with, for example:

        //modelBuilder.Entity<UserCustomer>()
        //    .HasKey(u => new { u.CustomerID, u.UserID }); //26 maj -17

        //modelBuilder.Entity<UserCustomer>()
        //.Property(f => f.UserCustomerID)
        //.ValueGeneratedOnAdd();

        //modelBuilder.Entity<UserCustomer>()
        //    .Property(c => c.UserCustomerID)
        //    .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);//TYY Stack Overflow

But this hasn't worked.

How do I make the UserCustomerID column auto-increment, as a key-column?

If I understand your question correctly, you just need the DatabaseGeneratedAttribue :

public class UserCustomer
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int UserCustomerID { get; set; }
}

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