2

アップデート

別のキーを追加すると機能することがわかりました。では、別のテーブルのキーと外部キーの両方ではないプロパティをどう処理するのでしょうか。

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

キーは同時に外部キーにすることができますが、1対多の関係にすることはできません。このマッピングでは...

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を持つ2つの行は存在できません。ただし、コレクションは同じ外部キーを持つすべての行によって定義されるため、関係の反対側にコレクションが存在することはできません。FKはユニークなので、多くの要素はあり得ません。

何を達成したいのかわかりませんが、1対1の関係を定義する必要があります(WithOptional(k => k.Property)たとえば、コレクションではなく参照WithMany(k => k.Properties)であるのでPropertyはなく)、または異なる外部キーが必要です(主)キープロパティから。

于 2012-10-20T12:36:15.897 に答える