【发布时间】:2013-05-15 11:35:41
【问题描述】:
我有一个表,其中有两个外键指向同一个父表 Edge.StartStationId 和 Edge.EndStationId。
我正在尝试将这些映射到实体框架中的对象,但找不到似乎可以解决问题的解决方法。 我在父级(Station)上找到了一些使用 2 个集合的解决方案,我对此不感兴趣。
站(父)类:
public partial class Station
{
public Station()
{
this.Reservations = new List<Reservation>();
this.StationMaintenances = new List<StationMaintenance>();
}
public int ID { get; set; }
public int TypeId { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public decimal StationLat { get; set; }
public decimal StationLong { get; set; }
public bool IsOperational { get; set; }
public bool IsActive { get; set; }
public DateTime CreatedDate { get; set; }
public virtual BatteryStorage BatteryStorages { get; set; }
public virtual List<Reservation> Reservations { get; set; }
public virtual List<StationMaintenance> StationMaintenances { get; set; }
public virtual List<Edge> Edges { get; set; }
public virtual StationType StationType { get; set; }
}
边缘(子)类:
public partial class Edge
{
public int ID { get; set; }
public int StartStationId { get; set; }
public virtual Station StartStation { get; set; }
public int EndStationId { get; set; }
public virtual Station EndStation { get; set; }
public decimal Distance { get; set; }
public decimal Time { get; set; }
public bool IsActive { get; set; }
}
边图类,在 OnModelCreating 中添加。
public EdgeMap()
{
// Primary Key
this.HasKey(t => t.ID);
// Properties
// Table & Column Mappings
this.ToTable("Edges");
this.Property(t => t.ID).HasColumnName("ID");
this.Property(t => t.StartStationId).HasColumnName("StartStationId");
this.Property(t => t.EndStationId).HasColumnName("EndStationId");
this.Property(t => t.Distance).HasColumnName("Distance");
this.Property(t => t.Time).HasColumnName("Time");
this.Property(t => t.IsActive).HasColumnName("IsActive");
// Relationships
//this.HasOptional(t => t.StartStation)
// .WithMany(t => t.Edges)
// .HasForeignKey(d => d.StarStationId);
//this.HasOptional(t => t.EndStation)
// .WithMany(t => t.Edges)
// .HasForeignKey(d => d.EndStationId);
}
例外:
在模型生成过程中检测到一个或多个验证错误: System.Data.Entity.Edm.EdmAssociationType::多重性与关系“Edge_EndStation”中角色“Edge_EndStation_Target”中的引用约束冲突。由于 Dependent Role 中的所有属性都不可为空,因此 Principal Role 的复数必须为“1”。
【问题讨论】:
-
我认为 EF 在对 Edges 集合进行持久更改时可能会感到困惑,所以我认为 EF 不会让你这样做。我认为您最终可能会得到两个边缘集合或非虚拟边缘集合,您可以手动从工作站集合中加载边缘。
标签: c# linq entity-framework linq-to-entities