实体框架中同一实体一对一和一对多 [英] One-to-one and one-to-many on the same entity in Entity Framework
本文介绍了实体框架中同一实体一对一和一对多的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我尝试了不同的方式将一个实体同时映射为one-to-one
和one-to-many
,但是我没有运气.
I tried different ways to map an entity as one-to-one
and one-to-many
at the same time, but I had no luck.
我在这里提供了我的模型:
I provided my models here:
public class Office
{
public virtual Person Manager {get; set;}
public virtual List<Person> People {get; set;}
}
public class Person
{
public virtual Office Office{get;set;}
}
有人可以指导我通过流利的api编写映射吗?
Could anybody guide me to write mapping via fluent api?
推荐答案
不必为特定实体定义两个不同的映射.我需要的是通过流利的api映射one-to-many
关系.
It's not necessary to define two different mapping for specific entities. All I need was to map a one-to-many
relation via fluent api.
以下是更改:
public class Office
{
// fk field to the entity
public Guid ManageId{get;set;}
public virtual Person Manager {get; set;}
public virtual List<Person> People {get; set;}
}
public class Person
{
// fk field to the entity
public virtual Guid OfficeId{get;set;}
public virtual Office Office{get;set;}
}
并使用流利的api:
modelBuilder.Entity<Office>()
.HasMany(d => d.People)
.WithOptional(s => s.Manager)
.Map(cs => cs.MapKey("OfficeId"));
这篇关于实体框架中同一实体一对一和一对多的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文