问题
I have two tables having composite pk's. The pk of TABLE1 goes into TABLE2 and they have a one to one optional relationship i.e TABLE1 may have 1 TABLE2 or 0 TABLE2. I get the following exception on model creation when I insert data.
The specified association foreign key columns 'third_table_id, fourth_table_id' are invalid. The number of columns specified must match the number of primary key columns.
Any help would be appreciated. The pk's of the table 1 come from table 3
I have defined the mapping TABLE1 as: #region PROPERTIES
Property(p => p.THIRDTABLEID).HasColumnName("third_table_id").HasDatabaseGeneratedOption(DatabaseGeneratedOption.None).IsRequired();
Property(p => p.FOURTHTABLEID).HasColumnName("fourth_table_id").HasDatabaseGeneratedOption(DatabaseGeneratedOption.None).IsRequired();
Property(p => p.SEQID).HasColumnName("Seq_ID").HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity).IsRequired();
#endregion PROEPRTIES
#region IGNORE
Ignore(p => p.RowState);
#endregion IGNORE
#region IGNORE
ToTable("dbo.TABLE1");
#endregion IGNORE
#region KEYS
// HasKey(t => new { t.THIRDTABLEID, t.FOURTHTABLEID });
HasKey(t => t.THIRDTABLEID);
HasKey(t => t.FOURTHTABLEID);
#endregion KEYS
#region RELATIONSHIPS
//relationship
HasRequired(t => t.THIRDTABLEID).WithMany(c => c.TABLE1).HasForeignKey
(t => t.THIRDTABLEID).WillCascadeOnDelete(false);
//relationship
HasRequired(t => t.SESN).WithMany(c => c.TABLE1).HasForeignKey
(t => t.SESSIONID).WillCascadeOnDelete(false);
#endregion RELATIONSHIPS
and the other TABLE2 as:
#region PROPERTIES
Property(p => p.BPROLEDETLID).HasColumnName("bp_role_detl_id").HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity).IsRequired();
Property(p => p.THIRDTABLEID).HasColumnName("third_table_id").HasDatabaseGeneratedOption(DatabaseGeneratedOption.None).IsRequired();
Property(p => p.FOURTHTABLEID).HasColumnName("fourth_table_id").HasDatabaseGeneratedOption(DatabaseGeneratedOption.None).IsRequired(); ;
Property(p => p.abc).HasColumnName("abc").IsOptional();
#endregion PROPERTIES
#region IGNORE
Ignore(p => p.RowState);
#endregion IGNORE
#region TABLE MAPPING
ToTable("dbo.TABLE2");
#endregion
#region KEYS
HasKey(t => new {t.THIRDTABLEID, t.FOURTHTABLEID});
//HasKey(t => t.THIRDTABLEID);
//HasKey(t => t.FOURTHTABLEID);
#endregion KEYS
#region RELATIONSHIPS
//relationship
HasRequired(t => t.TABLE1).WithOptional(c => c.TABLE1_DETL).Map(
m=> m.MapKey(
"third_table_id",
"fourth_table_id"
)).WillCascadeOnDelete(false);
#endregion RELATIONSHIPS
回答1:
Your first table is using HasKey twice, instead of creating a composite key. The second statement is just going to override the first one, so it looks like Table 1 has a single primary key, while Table 2 has a composite key of two columns. That's why it's telling you the number of columns must match.
来源:https://stackoverflow.com/questions/28173341/the-number-of-columns-specified-must-match-the-number-of-primary-key-columns-ef