4

I am working on converting a database-first project to code-first.

I have the following class and I am using EF Core 2.0:

public class WorkUser
{
    public int WorkUserId { get; set; }

    public int UserId { get; set; }
}

I tried the following and not sure whether it is correct.

public class WorkUser
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int WorkUserId { get; set; }

    [Key]
    public int UserId { get; set; }
}

I want the WorkUserId as an autoincrement property and UserId as primary key. The UserId value is coming from another table. So want this to be primary key but without autoincrement.

How to achieve this?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Mukil Deepthi
  • 6,072
  • 13
  • 71
  • 156
  • Have you actually tried your code? What does it generate? – Chris Pickford Jan 10 '18 at 10:41
  • What is `BaseEntity`? Are you having problems, if so what are they? Right now, this isn't really a question. – DavidG Jan 10 '18 at 10:42
  • This [should work as you expect](https://stackoverflow.com/a/10427810/33051) but you will need to ensure that you're setting the `UserId` to a valid, unique value. If this table has a many-to-many relationship you'll need [a composite key](https://stackoverflow.com/q/19792295/33051) formed of both the `UserId` and the `WorkUserId` (i.e. add a `Key` attribute and a `Column` attribute with an `Order` property.) – Zhaph - Ben Duguid Jan 10 '18 at 10:49
  • 1
    @Zhaph-BenDuguid Thanks. this table is not going to have many-to-many relationship. – Mukil Deepthi Jan 10 '18 at 11:12
  • @DavidG i have updated by removing the baseentity. – Mukil Deepthi Jan 10 '18 at 11:12
  • Have you considered using EF Core Power Tools? – ErikEJ Jan 10 '18 at 16:39

3 Answers3

2

The following worked as i expected:

public class WorkUser
{
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int WorkUserId { get; set; }

        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.None)]
        public int UserId { get; set; }
}
Mukil Deepthi
  • 6,072
  • 13
  • 71
  • 156
2

Try this:

public class SampleContext:DBContext{
public DbSet<WorkUser> WorkUsers{ get; set; }

protected override void OnModelCreating(ModelBuilder modelBuilder){
    modelBuilder.Entity<WorkUser>()
        .Property(p => p.WorkUserId )
        .ValueGeneratedOnAdd();
 }
}
El7or
  • 334
  • 1
  • 5
  • 18
0

In EF Core you should use the Sequence for the solution.

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

And than you configure your onModelBuilder:

modelBuilder.HasSequence<int>("ProjectId").StartsAt(100).IncrementsBy(1);
modelBuilder.Entity< Project>().Property(o => o.ProjectId).HasDefaultValueSql("NEXT VALUE FOR ProjectId");

or you can read more on the docs.

error505
  • 1,126
  • 1
  • 17
  • 29