实体框架中的属性是否可以是key和ForeignKey

Pou*_*sen 2 entity-framework

UPDATE

我发现添加一个单独的键可以使它工作.那么,对于一个不是关键属性的属性和对另一个表的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();
    }
}
Run Code Online (Sandbox Code Playgroud)

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

    }
}
Run Code Online (Sandbox Code Playgroud)

Sla*_*uma 6

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

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

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

我不知道你想要实现什么,但你要么需要定义一对一的关系(WithOptional(k => k.Property)例如代替WithMany(k => k.Properties),哪里Property引用,而不是集合)或者你需要有一个不同的外键来自(主要)密钥属性.