mskuratowski
mskuratowski

Reputation: 4124

Entity Framework One to many fluent Api - foreign key

I would like to make connection between two entitites.

I have Entity_1 and Entity_2 with relationship one - to many (one Entity_1 can have multiple Entity_2).

So I have my entities: Entity

    class Entity_1
    {    
        public int Id { get; set; }
        public int Entity_2Id{ get; set; }
        public virtual Entity_2 Entity_2{ get; set; } 
    }

    class Entity_2
    {    
        public int Id { get; set; }
        public int Entity_2Id{ get; set; }
        public virtual ICollection<Entity_1> Entity_1s{ get; set; }
    }

How Can I make connection that I have foreign key (Entity_1) in Entity 2 ?

Upvotes: 0

Views: 790

Answers (1)

Dennis
Dennis

Reputation: 37780

one Entity_1 can have multiple Entity_2

This means, that Entity_1 (optionally) has a collection of Entity_2, and Entity_2 (optionally) has a reference to Entity_1:

class Entity_1
{    
    public int Id { get; set; }
    public virtual ICollection<Entity_2> Entity_2s{ get; set; }
}

class Entity_2
{    
    public int Id { get; set; }
    public int Entity_1Id { get; set; }
    public virtual Entity_1 Entity_1 { get; set; }
}

while your entities are incorrect. Fluent API for the code above is:

HasRequired(_ => _.Entity_1)
    .WithMany(_ => _.Entity_2s)
    .HasForeignKey(_ => _.Entity_1Id);

More options available here.

Upvotes: 1

Related Questions