One person has One Title. (A title can be Mr. Mrs, Dr. etc). When I am trying to save this record (Code not Included), I am getting the following error.
InnerException = {"Cannot insert duplicate key row in object 'dbo.Persons' with unique index 'IX_Persons_TitleId'. The duplicate key value is (1).\r\nThe statement has been terminated."}
When debugging, I noticed that the Person object, has the Title object saved within it and the Title object again has the Person object in it. It goes on and on. I think this error is due to this. Anyway, I have attached the Model classes and Entity Configuration class. There might be something o do with the EntityConfiguration class. Please help
public class Title: Entity
{
public int Id { get; set; }
public string Name{ get; set; }
public Person Person { get; set; }
}
public class Person: Entity
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public int TitleId { get; set; }
public Title Title { get; set; }
}
public class PersonEntityConfiguration : IEntityTypeConfiguration<Person>
{
public void Configure(EntityTypeBuilder<Doctor> builder)
{
builder.ToTable("Persons");
builder.HasKey(c => c.Id);
builder.HasOne(c => c.Title)
.WithOne(c => c.Person)
.HasForeignKey<Person>(cc => cc.TitleId)
.OnDelete(DeleteBehavior.Restrict);
}
}
CODE FOR SAVING
_dbContext.Set<Person>().Add(entity);
await _dbContext.SaveChangesAsync();
HOW ENTITY IS CREATED
var person = MyMapper.Mapper.Map<Person>(request);
Title title = await _titleRepository.GettitleById(person.TitleId);
person.Title = title;
...
_dbContext.Set<Person>().Add(entity);
await _dbContext.SaveChangesAsync();
entityis created? How do you get the title for it?