我遇到了麻烦,我有两个具有Node StartNode属性的Route entite
第二个节点是StartNode。
起始节点和结束节点应该与Route有关系,但是当我尝试这样做时,我得到了一个例外:Cannot create a relationship between 'Node.Route' and 'Route.EndNode', because there already is a relationship between 'Node.Route' and 'Route.StartNode'. Navigation properties can only participate in a single
relationship.
路径实体有两个对象Node,分别代表起点和终点:
public class Route
{
public Guid DailyRouteId { get; set; }
public DailyRoute DailyRoute { get; set; }
public Node StartNode { get; protected set; }
public Node EndNode { get; protected set; }
public Guid EndNodeId { get; set; }
public Guid StartNodeId { get; set; }
}
Node实体:
public class Node
{
[Key]
public Guid Id { get; set; }
public string Address { get; protected set; }
public double Longitude { get; protected set; }
public double Latitude { get; protected set; }
public DateTime UpdatedAt { get; protected set; }
public Route Route { get; set; }
}
这是模型构建器:
modelBuilder.Entity<Route>()
.HasOne(x => x.StartNode)
.WithOne(x => x.Route)
.HasForeignKey<Route>(x => x.StartNodeId)
.OnDelete(DeleteBehavior.Restrict);
modelBuilder.Entity<Route>()
.HasOne(x => x.EndNode)
.WithOne(x => x.Route)
.HasForeignKey<Route>(x => x.EndNodeId)
.OnDelete(DeleteBehavior.Restrict);
答案 0 :(得分:0)
您需要为每个关系创建一个导航属性:
public class Node
{
[Key]
public Guid Id { get; set; }
public string Address { get; protected set; }
public double Longitude { get; protected set; }
public double Latitude { get; protected set; }
public DateTime UpdatedAt { get; protected set; }
public Route StartRoute { get; set; }
public Route EndRoute { get; set; }
}
modelBuilder.Entity<Route>()
.HasOne(x => x.StartNode)
.WithOne(x => x.StartRoute)
.HasForeignKey<Route>(x => x.StartNodeId)
.OnDelete(DeleteBehavior.Restrict);
modelBuilder.Entity<Route>()
.HasOne(x => x.EndNode)
.WithOne(x => x.EndRoute)
.HasForeignKey<Route>(x => x.EndNodeId)
.OnDelete(DeleteBehavior.Restrict);