我似乎無法理解EF如何處理複合鍵。當我嘗試'add-migration Initial'時,下面的代碼返回「屬性'QuestionID'不能用作實體QuestionQuestionTypesModel的關鍵屬性,因爲屬性類型不是有效的鍵類型,只有標量類型,字符串和字節[]是支持的鍵類型。「EF中的複合鍵
我也嘗試設置註釋而不是重寫OnModelCreating。我用[鑰匙,列(訂單= 0)]
任何人都可以給我任何線索什麼我做錯了嗎?或者解釋發生了什麼以更好地理解手頭的問題?
public class QuestionModel
{
[Key]
[HiddenInput(DisplayValue = false)]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public Guid ID { get; set; }
[Required]
[StringLength(250)]
public string Question { get; set; }
}
public class QuestionTypeModel
{
[Key]
[HiddenInput(DisplayValue = false)]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public Guid ID { get; set; }
[Required]
[StringLength(250)]
public string TypeName { get; set; }
}
public class QuestionQuestionTypesModel
{
public virtual QuestionModel QuestionID {get;set;}
public virtual QuestionTypeModel QuestionTypeID { get; set; }
}
public class InnuendoContext : DbContext
{
public IContext() : base("DefaultConnection")
{
}
public DbSet<QuestionTypeModel> QuestionTypes { get; set; }
public DbSet<QuestionModel> Questions { get; set; }
public DbSet<QuestionQuestionTypesModel> QuestionQuestionTypes { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
modelBuilder.Entity<QuestionQuestionTypesModel>().HasKey(a => new { a.QuestionID, a.QuestionTypeID });
}
}
什麼是'CModel'中的'A'和'B'? – JotaBe
它們是表A和B的外鍵。 – user1203996
此示例代碼不會編譯。沒有定義'A'和'B',除非你說出他們到底是什麼。請用工作代碼更新您的示例。如果沒有,我會要求結束這個問題。 – JotaBe