Using Blazor server-side UI with Entity Framework Core.
I have a Student table. One student can have multiple tests assigned, each test has test subject type which is FK to another lookup table.
public class Student{ public int Id { get; set;} public virtual ICollection<TestDetail > TestDetails{ get; set; } = new List< TestDetail >();}public class TestDetail{ public int StudentId { get; set; } public virtual Student Student { get; set; } = null!; public int? SubjectTypeId { get; set; } public virtual SubjectType? SubjectType { get; set; } = null!;}public class TestDetailConfiguration{ entity.Property(e => e. SubjectTypeId).HasColumnName("SUBJECT_TYPE_CD"); entity.HasOne(d => d. SubjectType).WithMany() .HasForeignKey(d => d.TestSubjectTypeId) .HasConstraintName("FK_NAME_TO_SUBJECT_TABLE"); entity.HasOne(d => d.Student).WithMany(p => p. TestDetails) .HasForeignKey(d => d.StudentId) .OnDelete(DeleteBehavior.ClientCascade) .HasConstraintName("FK_T_...");}In the UI, user can add multiple tests to a student at one time. Subject can be picked from a dropdown which populated with list of subjects from the Subject table.
Clicking on the AddTest button creates an object of type TestDetail and SubjectType is assigned with the test subject.
Populate the dropdown by querying the data context from a service class where factory is injected
public List<SubjectType> GetSubjects(){ using (var _context = factory.CreateDbContext()) { var rows = _context.Set<Subject>(); return rows; }}The UI page has:
[Inject]private IDbContextFactory<DBContext> factory { get; set; }private DBContext _dbContext;private IEnumerable<SubjectType> subjecteTypes = [];private void Onintialized(){ _dbContext = factory.CreateDbContext(); subjectTypes = Service.GetSubjects(); Student student = new Student(); _dbContext.Students.Add(student);}On add test button click, creates a TestDetail object and adds to the collection.
student.TestDetails.Add(new TestDetail());Then later its SubjectType is populated with the selected subject from the dropdown with values "1 – English", "2 – Science".
When I add two tests with the same subject "1 - English", Entity Framework Core always throwing this exception on save:
The instance of entity type cannot be tracked because another instance of this type with the same key {1} is already being tracked.
I tried using .AsNoTracking() while getting the Subject list, but that didn't work either.
Thanks