2

更新

我发现添加一个单独的键可以使它工作。那么,如果一个属性既不是另一个表的键又不是 ForeignKey 怎么办?

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();
    }
}

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();

    }
}
4

1 回答 1

6

一个键可以同时是一个外键,但不能是一对多的关系。在这个映射...

HasKey(t => new { t.QuestionId, t.TrafficImageGuid });
HasRequired(t => t.TrafficImageQuestion)
    .WithMany(k => k.Properties)
    .HasForeignKey(t => new { t.QuestionId, t.TrafficImageGuid });

...您定义键 ( t.QuestionId, t.TrafficImageGuid) 也是外键。但这意味着这个外键在整个表中必须是唯一的(因为主键是唯一的)。不能有两行具有相同的 FK。但这意味着关系的另一端不能有集合,因为集合是由具有相同外键的所有行定义的。由于 FK 是唯一的,因此元素不能太多。

我不知道你想要实现什么,但你要么需要定义一个一对一的关系(WithOptional(k => k.Property)例如,而不是WithMany(k => k.Properties), where Propertyis a reference,而不是一个集合)或者你需要一个不同的外键从(主)键属性。

于 2012-10-20T12:36:15.897 回答