C# 实体框架5-对同一表的多个外键的关系多重性约束
我正在做一个需要更新EntityFramework5的项目。这需要对实体和配置类进行一些细微的更改(代码优先),以使数据层保持最新。升级已完成,只剩下一个实体。执行此实体的查询时,我遇到以下错误:C# 实体框架5-对同一表的多个外键的关系多重性约束,c#,entity-framework,constraints,foreign-key-relationship,multiplicity,C#,Entity Framework,Constraints,Foreign Key Relationship,Multiplicity,我正在做一个需要更新EntityFramework5的项目。这需要对实体和配置类进行一些细微的更改(代码优先),以使数据层保持最新。升级已完成,只剩下一个实体。执行此实体的查询时,我遇到以下错误: System.InvalidOperationException: A relationship multiplicity constraint violation occurred: An EntityReference can have no more than one related objec
System.InvalidOperationException: A relationship multiplicity constraint violation occurred: An EntityReference can have no more than one related object, but the query returned more than one related object. This is a non-recoverable error.
实体为一个表建模,该表包含两个可选的外键,它们与数据库中的另一个表相关
以下是数据库中表的一部分外观(首先是有问题的表):
在此模型中,LocationMap.SourceId和LocationMap.TargetId都引用Location.Id。以下是用于在我的数据层中表示此关系的实体和配置类的部分:
public class LocationMap
{
public int Id { get; set; }
public int SourceId { get; set; }
public int TargetId { get; set; }
...
public virtual Location Source { get; set; }
public virtual Location Target { get; set; }
}
public class Location
{
public int Id { get; set; }
...
public virtual ICollection<LocationMap> TargetMaps { get; set; }
public virtual ICollection<LocationMap> SourceMaps { get; set; }
}
public LocationMapConfiguration()
{
HasKey(x => x.Id);
HasRequired(map => map.Source)
.WithMany(location => location.SourceMaps)
.HasForeignKey(map => map.SourceId)
.WillCascadeOnDelete(false);
HasRequired(map => map.Target)
.WithMany(location => location.TargetMaps)
.HasForeignKey(map => map.TargetId)
.WillCascadeOnDelete(false);
}
public LocationConfiguration()
{
HasKey(x => x.Id);
...
}
。。。map.Source.Name起作用,而map.Target.Name产生上述异常。如何调用这两个映射并不重要—源始终工作,目标始终抛出异常
原始位置实体类没有定义ICollection导航属性,事实上,这是我在创建更新的数据层时设置该属性的方式。正是在为例外情况进行研究时,多个源(包括这里的几个)涉及到以示例中显示的方式实现导航属性的解决方案。因此,我添加了它们,但它并没有解决我的问题
如往常一样,在此方面的任何帮助都将不胜感激
谢谢
public class LocationMap
{
public int Id { get; set; }
public int SourceId { get; set; }
public int TargetId { get; set; }
...
public virtual Location Source { get; set; }
public virtual Location Target { get; set; }
}
public class Location
{
public int Id { get; set; }
...
public virtual ICollection<LocationMap> TargetMaps { get; set; }
public virtual ICollection<LocationMap> SourceMaps { get; set; }
}
public LocationMapConfiguration()
{
HasKey(x => x.Id);
HasRequired(map => map.Source)
.WithMany(location => location.SourceMaps)
.HasForeignKey(map => map.SourceId)
.WillCascadeOnDelete(false);
HasRequired(map => map.Target)
.WithMany(location => location.TargetMaps)
.HasForeignKey(map => map.TargetId)
.WillCascadeOnDelete(false);
}
public LocationConfiguration()
{
HasKey(x => x.Id);
...
}
using (var context = new MyDbContext())
{
var map = context.LocationMaps
.FirstOrDefault();
Logger.Info("Source name: {0}", map.Source.Name);
Logger.Info("Target name: {0}", map.Target.Name);
}