简体   繁体   English

同一实体之间的EF一对一和一对多

[英]EF One-To-One and One-To-Many between same entities

I have the following problem: I need to create entities, which will be connected with One-To-Many and One-To-One relationships in Entity Framework at the same time. 我有以下问题:我需要创建实体,这些实体将同时与Entity Framework中的一对多和一对一关系连接。

The model I want to create is following: I have MapObject entity and there FloorMap entity. 我要创建的模型如下:我有MapObject实体,还有FloorMap实体。 There are many MapObjects on the FloorMap, but FloorMap is a part of another MapObject. FloorMap上有许多MapObject,但是FloorMap是另一个MapObject的一部分。 How can I implement it? 我该如何实施?

I thought about doing somtheing like this: 我考虑过做这样的事情:

public class FloorMap
{

    public int FloorMapID { get; set; }

    public int FloorNumber { get; set; }

    public string FloorImage { get; set; }

    public string FloorMapDescription { get; set; }

    public virtual List<MapObject> MapObjects { get; set; }

    public virtual MapObject MapObject { get; set; }
}

public partial class MapObject
{
    [Key,ForeignKey ("FloorMap")]
    public int FloorMapRefID { get; set; }

    public virtual FloorMap FloorMap { get; set; }
}

Unfortunately, that doesn't work the way I want it to. 不幸的是,这并不符合我的期望。 Is there any way to implement such relationships in EF? 有什么方法可以在EF中实现这种关系?

Im not really sure I understand what you are asking but it sounds like you want a floor map to have one parent and many children. 我不太确定我是否理解您的要求,但听起来您希望一张楼层地图有一个父母和多个孩子。 Im not too sure why you want MapObject in the mix with this but sure. 我不太确定为什么要与此混用MapObject,但可以肯定。

public class FloorMap
{
    public int FloorMapID { get; set; }
    public int FloorNumber { get; set; }
    public string FloorImage { get; set; }
    public string FloorMapDescription { get; set; }
    public virtual List<MapObject> MapObjects { get; set; }
    public virtual MapObject MapObject { get; set; }
}

public partial class MapObject
{
    [Key,ForeignKey ("FloorMap")]
    public int FloorMapRefID { get; set; }
    public virtual FloorMap FloorMap { get; set; }
    public int OtherFloorMapRefID {get;set;}
    public virtual FloorMap OtherFloorMap { get; set; }
}


modelBuilder.Entity<FloorMap>().HasMany(e => e.MapObjects).WithRequired(e=>e.OtherFloorMap).HasForeignKey(e=>e.OtherFloorMapRefID);
modelBuilder.Entity<FloorMap>().HasOptional(e => e.MapObject).WithRequired(e=>e.FloorMap);

Does this look like what you are trying to do? 这看起来像您要执行的操作吗?

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

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