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.