Esteban
Esteban

Reputation: 3139

Entity Framework: Fluent API. How should I map this relationship?

My table is as follows:

create table Entities(
    EntityId bigint not null identity(1, 1),
    Name nvarchar(64) not null,
    ParentEntityId bigint null
)
alter table Entities add constraint PK primary key (EntityId)
alter table Entities add constraint FK foreign key (ParentEntityId) references Entities(EntityId)

My model looks like this:

public class Entity
{
    [Required]
    public virtual long EntityId { get; set; }

    [Required]
    public virtual string Name { get; set; }

    public virtual long? ParentEntityId { get; set; }

    public virtual Entity ParentEntity { get; set; }
}

and I'm trying to map the ParentEntity property with fluent api mapping, but I couldn't get this to work. How can I do it?
Thanks in advance!

EDIT: Fixed code discrepancy.

Upvotes: 0

Views: 346

Answers (1)

Mark Oreta
Mark Oreta

Reputation: 10416

This fluent will work for you:

        modelBuilder.Entity<Entity>()
            .HasOptional(e => e.ParentEntity)
            .WithMany()
            .HasForeignKey(e => e.ParentEntityId );

Created this database for me:

enter image description here

Upvotes: 2

Related Questions