简体   繁体   English

实体框架:Fluent API。 我应该如何映射这种关系?

[英]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. 我正在尝试使用流畅的api映射映射ParentEntity属性,但我无法使其工作。 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: 为我创建了这个数据库:

在此输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用实体框架流利的API配置这种关系? - How using entity framework fluent API to config such relationship? 如何使用流利的api定义复杂的(1到0 | n)实体框架关系? - How to define a complex (1 to 0|n) entity framework relationship with fluent api? 实体框架6与流利api的0.1到0.1关系 - Entity Framework 6 0.1 to 0.1 relationship with fluent api 与Entity Framework Fluent API的一对一关系 - One to one relationship with Entity Framework Fluent API 实体框架Fluent API关系语法 - Entity Framework Fluent API Relationship Syntax 如何使用实体框架和Fluent API映射复杂的一对多 - How to map complex one-to-many with Entity Framework and Fluent API Entity framework fluent api 如何从 class 属性动态到 map - Entity framework fluent api how to map dynamically from class attribute 如何在实体框架中创建此关系? - How should I create this relationship in Entity Framework? 如何使用实体框架 4.1“仅代码”流利的 API map char 属性? - How do I map a char property using the Entity Framework 4.1 "code only" fluent API? 如何在ASP.NET MVC 5,Entity Framework 6中使用流畅的API映射表? - How can I map tables using fluent API in ASP.NET MVC 5, Entity Framework 6?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM