简体   繁体   中英

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.

This fluent will work for you:

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

Created this database for me:

在此输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM