0

I have two tables with the details as shown here, which have a one-to-one relationship with one another.

public partial class Concept : AuditableWithBaseEntity<decimal>
{
    public string Code { get; set; }
    public decimal ConceptnodeId { get; set; }
    public virtual Conceptnode Conceptnode { get; set; }
}

public partial class Conceptnode : BaseEntity<decimal>
{
    public decimal ConceptId { get; set; }
    public int Presentationorder { get; set; }

    public virtual Concept Concept { get; set; }
}

When I try to insert data with this code:

Concept targetConcept = new()
{
    Code = currTC.Code,
    Conceptnode = new Conceptnode()
                      {
                          presentationOrder = currTC.presentationOrder
                      }
};

_dbContext.Concepts.Add(targetConcept)
_dbContext.SaveChanges();

I get an error:

An error occurred while saving the entity changes. See the inner exception for details.

The INSERT statement conflicted with the FOREIGN KEY constraint "conceptnls_fk2". The conflict occurred in database "DB_P20", The statement has been terminated.

Is there any other way to use for such scenario.

Thanks in advance.

jps
  • 20,041
  • 15
  • 75
  • 79
  • https://stackoverflow.com/questions/75563429/how-do-i-create-a-one-to-one-mapping-without-using-a-foreign-key-constraint/75571095#75571095 **this link is different about your problem, but I think is useful for read.** – Soheil Mar 01 '23 at 07:59

1 Answers1

0

I don't know about your mapping and how you create your decimal Id, but try this.

  protected override void OnModelCreating(ModelBuilder modelBuilder)
  {
      modelBuilder.Entity<Concept>()
          .HasOne(t => t.Conceptnode)
          .WithOne(t => t.Concept)
          .HasForeignKey<Concept>(t => t.ConceptnodeId)
          .IsRequired(false);
  } 
Soheil
  • 190
  • 1
  • 1
  • 14
  • thank you. I have established the one to one relationship between the tables using FluentAPI, problem issue when i send the data to database data EF core doesn't create record in the database. – Ghiasuddin Tajwal Mar 01 '23 at 10:48
  • So, please add more detail from your code. – Soheil Mar 01 '23 at 10:54