Entity framework 7 (core) RC2 many-to-many relationship with itself and query

混江龙づ霸主 提交于 2019-12-14 02:56:47

问题


Is it possible to create an entity Socket with many-to-many relationship for itself?

The typical PostTag example I am familiar from the EF Core documentation. However, I'm not quite sure how to create this kind of relationship with only one entity and one intermediate table SocketSocket.

Here's example:

modelBuilder.Entity<SocketSocket>()
    .HasKey(ss => new { ss.SocketToId, ss.SocketFromId});
modelBuilder.Entity<SocketSocket>()
    .HasOne(ss => ss.SocketTo)
    .WithMany(s => s.ConnectedToSockets)
    .HasForeignKey(ss => ss.SocketToId);
modelBuilder.Entity<SocketSocket>()
    .HasOne(ss => ss.SocketFrom)
    .WithMany(s => s.ConnectedToSockets)
    .HasForeignKey(ss => ss.SocketFromId);

How can I then use this model properly; add connections and query?

Adding relationship ?

var joinTable = new SocketSocket
{
    SocketToId = socketTo.SocketId,
    SocketTo = socketTo,
    SocketFromId = socketFrom.SocketId,
    SocketFrom = socketFrom
};
DatabaseContext.SocketSockets.Add(joinTable);

Query ?

How to efficiently find all the sockets which are connected into one socket?

来源:https://stackoverflow.com/questions/37808131/entity-framework-7-core-rc2-many-to-many-relationship-with-itself-and-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!