[英]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.