I have an entity Group which has a many to many relationship with a view VesselInfo. In database, the relationship is stored in a table, GroupVessel.
public class Group
{
public Group()
{
GroupVessels = new List<GroupVessel>();
}
public int GroupId { get; set; }
public virtual ICollection<GroupVessel> GroupVessels { get; set; }
}
public class GroupVessel
{
public int GroupVesselId { get; set; }
public int GroupId { get; set; }
public virtual Group Group { get; set; }
public int VesselId { get; set; }
public virtual VesselView Vessel { get; set; }
}
public class VesselView
{
public int VesselId { get; set; }
}
The entities are mapped in the context like this:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new VesselViewMapping());
modelBuilder.Configurations.Add(new GroupMapping());
modelBuilder.Configurations.Add(new GroupVesselMapping());
base.OnModelCreating(modelBuilder);
}
public class VesselViewMapping : EntityTypeConfiguration<VesselView>
{
public VesselViewMapping()
{
// Primary Key
HasKey(t => t.VesselId);
// Properties
Property(t => t.VesselId)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
// Table & Column Mappings
ToTable("v_VesselInfo");
Property(t => t.VesselId).HasColumnName("VesselId");
}
}
public class GroupMapping : EntityTypeConfiguration<Group>
{
public GroupMapping()
{
// Primary Key
HasKey(group => group.GroupId);
// Properties
// Table & Column Mappings
ToTable("Group");
Property(t => t.GroupId)
.HasColumnName("GroupId")
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
}
}
public class GroupVesselMapping : EntityTypeConfiguration<GroupVessel>
{
public GroupVesselMapping()
{
// Primary Key
HasKey(group => group.GroupVesselId);
// Properties
// Table & Column Mappings
ToTable("GroupVessel");
Property(t => t.GroupVesselId)
.HasColumnName("GroupVesselId")
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
Property(t => t.VesselId).HasColumnName("VesselId").IsRequired();
Property(t => t.GroupId).HasColumnName("GroupId");
// Relationships
HasRequired(t => t.Group).WithMany(g => g.GroupVessels)
.HasForeignKey(t => t.GroupVesselId);
}
}
When I try to instantiate the context, I get the following error:
Exception Details: System.Data.Entity.ModelConfiguration.ModelValidationException: One or more validation errors were detected during model generation:
\tSystem.Data.Entity.Edm.EdmAssociationEnd: : Multiplicity is not valid in Role 'GroupVessel_Group_Source' in relationship 'GroupVessel_Group'. Because the Dependent Role refers to the key properties, the upper bound of the multiplicity of the Dependent Role must be '1'.
Some additional info: In database, the GroupVessel.VesselId column is a foreign key to a table Vessels, which is the underlying table of the v_VesselInfo view. There is no navigation property from VesselView back to GroupVessel as there is no need to traverse the graph that way in the application.