I'm working on a project that required an update to Entity Framework 5. This has required some slight changes to the entity and configuration classes (code first) to bring the data layer current. The upgrade is complete, except for one remaining entity. When executing queries for this entity, I'm getting the following error:
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.
The entity models a table that contains two optional, foreign keys that relate to another table in the database.
Here is a portion of what the tables look like in the database (first, the table in question):
LocationMap Location
----------- --------
Id (PK, not null) Id (PK, not null)
SourceId (FK, null) ...
TargetId (FK, null)
In this model, both LocationMap.SourceId and LocationMap.TargetId refer to Location.Id. Here is the portion of the entity and configuration classes used to represent this relationship in my data layer:
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);
...
}
When running the following code ...
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);
}
... map.Source.Name works, while map.Target.Name produces the exception above. It does not matter how the two mappings are called - Source always works and Target always throws the exception.
The original Location entity class did not have the ICollection navigational properties defined, and was in fact how I set this up when creating the updated data layer. It was in doing research for the exception that multiple sources (including several here) involved solutions implementing the navigational properties in the fashion displayed in the examples. Thus, I added them, but it has not resolved my issue.
As usual, any help on this would be greatly appreciated.
Thanks!