Reputation: 17540
UPDATE
I found out that adding a seperate key makes it work. So whats the deal with a property not being both key and ForeignKey to another table?
One or more validation errors were detected during model generation:
\tSystem.Data.Entity.Edm.EdmAssociationEnd: : Multiplicity is not valid in Role 'TrafficImageQuestionExtraInfo_TrafficImageQuestion_Source' in relationship 'TrafficImageQuestionExtraInfo_TrafficImageQuestion'. Because the Dependent Role refers to the key properties, the upper bound of the multiplicity of the Dependent Role must be '1'.
public class TrafficImageQuestionExtraInfoMap : EntityTypeConfiguration<TrafficImageQuestionExtraInfo>
{
public TrafficImageQuestionExtraInfoMap()
{
this.HasKey(t => new { t.QuestionId, t.TrafficImageGuid });
this.Property(t => t.TrafficImageGuid).IsRequired();
this.Property(t => t.QuestionId).IsRequired();
this.Property(t => t.Key).IsRequired().HasMaxLength(50);
this.Property(t => t.Value).IsRequired().IsUnicode().HasMaxLength(128);
HasRequired(t => t.TrafficImageQuestion).WithMany(k => k.Properties).HasForeignKey(t => new { t.QuestionId, t.TrafficImageGuid });//.Map(m => m.MapKey("QuestionId", "TrafficImageGuid")).WillCascadeOnDelete();
}
}
and
public class TrafficImageQuestionMap : EntityTypeConfiguration<TrafficImageQuestion>
{
public TrafficImageQuestionMap()
{
// Primary Key
this.HasKey(t => new { t.QuestionId, t.TrafficImageGuid });
// Table & Column Mappings
this.ToTable("TrafficImageQuestions");
this.Property(t=>t.QuestionId).IsRequired();
this.HasRequired(t => t.TrafficImage).
WithMany(t=>t.TrafficImageQuestions).
HasForeignKey(t=>t.TrafficImageGuid).WillCascadeOnDelete();
this.Property(t => t.
Answer).IsRequired();
}
}
Upvotes: 2
Views: 5264
Reputation: 177163
A key can be a foreign key at the same time, but not in a one-to-many relationship. In this mapping...
HasKey(t => new { t.QuestionId, t.TrafficImageGuid });
HasRequired(t => t.TrafficImageQuestion)
.WithMany(k => k.Properties)
.HasForeignKey(t => new { t.QuestionId, t.TrafficImageGuid });
...you define that the key (t.QuestionId, t.TrafficImageGuid
) is also a foreign key. But that means that this foreign key must be unique in the whole table (because the primary key is unique). There can't be two rows with the same FK. But that means that there can't be a collection on the other side of the relationship because the collection is defined by all rows which have the same foreign key. Since the FK is unique there can't be many elements.
I don't know what you want to achieve, but you either need to define a one-to-one relationship (WithOptional(k => k.Property)
for example instead of WithMany(k => k.Properties)
, where Property
is a reference, not a collection) or you need to have a foreign key that is different from the (primary) key property.
Upvotes: 6