属性不能同时是实体框架中的密钥和外键

时间:2012-10-20 06:07:33

标签: entity-framework

更新

我发现添加一个单独的密钥可以使它工作。那么,对于一个不是关键属性的外交和另一个桌子上的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();

    }
}

1 个答案:

答案 0 :(得分: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),其中Property引用,而不是集合)或者您需要具有与(主)键属性不同的外键。