0

So I have the following code:

ParentModel.cs

public class ParentModel {
   public int ParentModelID {get; set;}
   ...other fields here

   public ChildModel ChildModel {get; set;}
}

ChildModel.cs

public class ChildModel{
   [ForeignKey("ParentModel")]
   public int ChildModelID {get; set;}
   ...other fields and navigation properties here

   public int ParentModelID {get; set;}
   public ParentModel ParentModel {get; set;}
}

So the database gets generated successfully. The problem occurs when I try to save data. For example I save data to the ParentModel first and it gets save successfully. But when I save inside ChildModel, even when my data contains the ParentModel's id, it gives me the following error:

The INSERT statement conflicted with the FOREIGN KEY constraint "FK_dbo.ChildModels_dbo.ParentModels_ChildModelID". The conflict occurred in database "MyDatabaseName", table "dbo.ParentModels", column 'ParentModelID'. The statement has been terminated.

Jed
  • 1,054
  • 1
  • 15
  • 34

2 Answers2

1

use following with fluent api

public class ParentModel {

   public int ParentModelID {get; set;}
   ...other fields here
   public virtual ChildModel childModel {get; set;}

}


public class ChildModel{
   public int ParentModelID {get; set;}
   public int ChildModelID {get; set;}
   ...other fields and navigation properties here


   public virtual ParentModel parentModel {get; set;}
}

Then i will use fluent api to create relationship

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    // Configure ParentModelID as PK for ChildModel
    modelBuilder.Entity<ChildModel>()
        .HasKey(e => e.ParentModelID);

    // Configure ParentModelID as FK for ChildModel
    modelBuilder.Entity<ParentModel>()
                .HasOptional(s => s.childModel) 
                .WithRequired(ad => ad.ParentModelID); 

}
  • When I follow your answer I got the following error: `One or more validation errors were detected during model generation: ChildModel_ParentModel_Source: : Multiplicity is not valid in Role 'ChildModel_ParentModel_Source' in relationship 'ChildModel_ParentModel'. Because the Dependent Role properties are not the key properties, the upper bound of the multiplicity of the Dependent Role must be '*'.` – Jed Oct 05 '17 at 03:00
  • did you add [Key] fields to primary keys? – Shiwanka Chathuranga Oct 05 '17 at 03:02
  • Yes I did. I just copied your answer. – Jed Oct 05 '17 at 03:03
  • did you did my change to parentModel? – Shiwanka Chathuranga Oct 05 '17 at 03:05
  • No, I can't do it like that cause what I need is a One-to-One or One-to-Zero relationship. – Jed Oct 05 '17 at 03:06
  • Try the change now – Shiwanka Chathuranga Oct 05 '17 at 03:09
  • tell me if its not work, then i will edit with fluent APi – Shiwanka Chathuranga Oct 05 '17 at 03:12
  • No, i'm still getting the same `Multiplicity is not valid` error. – Jed Oct 05 '17 at 03:14
  • I see you also removed the `ForeignKey` annotation. When I removed that I got the ff. error: `Unable to determine the principal end of an association between the types 'ParentModel' and 'ChildModel'. The principal end of this association must be explicitly configured using either the relationship fluent API or data annotations.` – Jed Oct 05 '17 at 03:16
  • Now it does save both of them, but when I access them i'm getting the ff error: `Self referencing loop detected for property 'parentModel' with type 'ParentModel'` I've removed `virtual` and query the relationship using `Include`. – Jed Oct 05 '17 at 06:30
  • No, it's still not successful since I could access them. – Jed Oct 05 '17 at 06:38
  • according to this code no any self referencing loop, check your code, you may have fluent api things again in model level – Shiwanka Chathuranga Oct 05 '17 at 06:40
  • I think this is what's wrong, cause on my Fluent API I couldn't do it like your answer: `.WithRequired(ad => ad.ParentModelID)`. I am getting an error: `Cannot implicitly convert type int to 'ParentModel'`. So what I did instead was just put `WithRequired(ad => ad.ParentModel)`. I think that's what's causing this loop error. What do you think? – Jed Oct 05 '17 at 06:48
  • No it didn't, I said I think that could be the reason why it's giving me the loop error I stated above. I have no idea yet how to resolve it. – Jed Oct 05 '17 at 06:55
  • NO thats mapping.... send me your full code, upload to drop box and send the link – Shiwanka Chathuranga Oct 05 '17 at 06:56
0

You almost had it; you want a shared primary key, which you have set up. The problem is you are presumably setting the the ChildModel.ParentModelID property with the parent's ID. Remove that property and set ChildModel.ChildModelID to the ParentModelID of the Parent entity - ChildModelID is the FK to the ParentModel entity. You'll also need to make ChildModel.ParentModel required.

public class ParentModel 
{
   public int ParentModelID {get; set;}
   public ChildModel ChildModel {get; set;}
}

public class ChildModel
{
   [ForeignKey("ParentModel")]
   public int ChildModelID {get; set;}
   [Required]
   public ParentModel ParentModel {get; set;}
}

var parent = new ParentModel();
dbContext.Set<ParentModel>().Add( parent );
dbContext.SaveChanges();

var child = new ChildModel()
{
     ChildModelID = parent.ParentModelID
};
dbContext.Set<ChildModel>().Add( child );
dbContext.SaveChanges();

See this answer for another example.

Moho
  • 15,457
  • 1
  • 30
  • 31