.net “实体类型'JobConceptTranslationEntity'需要定义主键,如果您打算使用无键实体类型,请调用'HasNoKey'

u1ehiz5o  于 2023-10-21  发布在  .NET
关注(0)|答案(1)|浏览(150)

我有两个表,分别是JobConceptJobConceptTranslation。所以,两者有这样的关系:

[Table("JobConcept")]
public class JobConceptEntity : BaseEntity, IHasKey<Guid> {
  [Key]
  public Guid Id { get; set; }

  public string Name { get; set; }

  public virtual ICollection<JobConceptTranslationEntity> Translations { get; set; }
}

[Table("JobConceptTranslations")]
public class JobConceptTranslationEntity : TranslationEntity {
  [ForeignKey(nameof(JobConceptId))]
  public Guid JobConceptId { get; set; }

  public virtual JobConceptEntity JobConcept { get; set; }

  public string Name { get; set; }

  public string Language { get; set; }
}

无论如何,我已经在OnModelCreating上这样设置了主键:
modelBuilder.Entity().HasKey(x => new { x.JobConceptId,x. JobageCode});
但它不幸地给出了这个错误,“实体类型'JobConceptTranslationEntity'需要定义一个主键。如果要使用无键实体类型,请在“OnModelCreating”中调用“HasNoKey”。有关无键实体类型的更多信息,请参见https://go.microsoft.com/fwlink/?linkid=2141943.",
我试图添加public Guid? Id {get;set;}与[键]数据注解,并尝试新的migra数据库,但它给**“JobConceptTranslations”(错误号:150“Foreign key constraint is incorrectly formed”"**错误
所以,你能帮帮我吗,因为我真的被它困住了。

vfhzx4xs

vfhzx4xs1#

当你在依赖类中的外键属性上使用[ForeignKey(xxx)]属性时,你应该传递导航属性的名称,所以这里你应该使用[ForeignKey(nameof(JobConceptEntity))]
但是当你在依赖类中的navigation属性上使用[ForeignKey(xxx)]属性时,传递外键属性的名称:

[ForeignKey("JobConceptId")]
public virtual JobConceptEntity JobConcept { get; set; }

更多细节可以参考link

相关问题