0

I am using Entity Framework Core with ASP.NET Core with code first approach. Here is the simplified version. I have two entities Store and Shift. Shift is the dependent entity and there is one to Many Relationship between Store and shift.

Store Entity:

public partial class Store
    {
        [Display(Name = "Store Id")]
        public int Id { get; set; }
        [Display(Name = "Store Name")]
        public string Name { get; set; }
        public virtual ICollection<Shift> Shifts { get; set; } = new HashSet<Shift>();
}

The Shift Entity

public partial class Shift
    {
 public int Id { get; set; }
 public int StoreId { get; set; }
 [Display(Name = "Start Time")]
public TimeSpan? StartTime { get; set; }
public virtual GasStation GasStation { get; set; }
}

Following is fluent API configuration in DBContext

modelBuilder.Entity<Shift>().Property(t => t.StoreId)
    .ValueGeneratedNever().IsRequired();

modelBuilder.Entity<Shift>().Property(t => t.Id).ValueGeneratedOnAdd().IsRequired();

modelBuilder.Entity<Shift>()
.HasKey(k => new { k.GasStationId, k.Id });

Scenario and Goal I want to achieve following. A Store entity can have many shifts and shift number is assigned at the time when the Shift record is created (Identity column for Id).

  • Store 1: Let’s say I create a first shift for Store 1. The Shift Id will be assigned by the database is 1. If I create another shift for Store 1 the Shift Id is assigned as 2. So far so good.
  • Store 2: Now for Store 2 when I create the first shift the Id is assigned to value 3. I want it to have the Id value assigned to 1.

Simply I want the Id of Shift start from 1 for each store record. How can I achieve that? Thanks in advance for your help.

Sampath
  • 63,341
  • 64
  • 307
  • 441
Lion Foo
  • 37
  • 6

1 Answers1

0

Identity columns must contain unique values. Therefore it is not possible to assign the same value to the Primary Id of Shift more than once.

What you can do is use a composite key instead of a primary key for Shift.

Introduce a new column ShiftNumber. Then use this column + the id of Store as composite key (How do I map a composite primary key in Entity Framework 4 code first?).

Community
  • 1
  • 1
Georg Patscheider
  • 9,357
  • 1
  • 26
  • 36
  • @George Thanks for your response. I am already doing what you have suggested. If you look at the last line, there I am setting up the composite key modelBuilder.Entity() .HasKey(k => new { k.GasStationId, k.Id }); – Lion Foo Sep 06 '16 at 15:38
  • Sorry there is a type in the last code line it should be as follows 'modelBuilder.Entity() .HasKey(k => new { k.StoreId, k.Id });' – Lion Foo Sep 06 '16 at 15:46