Jed
Jed

Reputation: 1074

Configuring relationship in C# code first

So I have these models:

ParentModel.cs

public class ParentModel {
  ...properties here

  //relationship to Child
  [ForeignKey("ChildModelID")]
  public ChildModel ChildModel { get; set; }
}

ChildModel.cs

public class ChildModel{
  ...properties here

  //relationship to parent
  [ForeignKey("ParentModel")]
  public int? ParentModelID { get; set; }
  public ParentModel ParentModel { get; set; }
}

I'm using Web API Code-first. I am new to this. And I am getting the error below when the database is being created. But if I remove the navigation property in ParentModel (i.e. public ChildModel ChildModel { get; set; }) everything works fine, except that it doesn't fulfill my needs. I want to eager load (or lazy load not sure which term is right) the ChildModel when I get the ParentModel. The relationship here is Zero-or-One-to-One. Meaning the ChildModel can have a record that doesn't have a reference in ParentModel.

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 '*'.

Thank you in advance!

Upvotes: 0

Views: 94

Answers (2)

Dan Nguyen
Dan Nguyen

Reputation: 1358

ChildModel and ParentModel is One-to-Zero/One

UPDATED:

So let try this code

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

public class ParentModel
{
    //[ForeignKey("ChildModel")]
    //[Key]
    public int ChildModelId { get; set; }
    public ChildModel ChildModel { get; set; }
}

public class Context : DbContext
{
    public DbSet<ChildModel> ChildModels { get; set; }
    public DbSet<ParentModel> ParentModels { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<ParentModel>().HasKey(s => s.ChildModelId);

        modelBuilder.Entity<ParentModel>().HasRequired(s => s.ChildModel).WithOptional(s => s.ParentModel);
    }
}

Upvotes: 2

Daniel Hilgarth
Daniel Hilgarth

Reputation: 174467

I think you mixed up the ForeignKey attribute. Shouldn't it be on ParentModel and refer to ParentModelID?

public class ChildModel
{
    ...properties here

    //relationship to parent
    public int? ParentModelID { get; set; }
    [ForeignKey("ParentModelID")]
    public ParentModel ParentModel { get; set; }
}

Upvotes: 0

Related Questions