[英]Two foreign keys to one Entity Framework Core table
I am developing language dictionary with asp core 2.0. 我正在使用ASP Core 2.0开发语言词典。 I wonder how to properly design my database. 我想知道如何正确设计数据库。 I came across similar question: How to design a database for translation dictionary? 我遇到类似的问题: 如何设计翻译词典的数据库? . 。
I decided to create a database like in the following picture: 我决定创建一个数据库,如下图所示:
database structure that i wanna realize in ef core 我想在ef核心中实现的数据库结构
But i do not know how to realize this structure with entity framework core 2.0. 但是我不知道如何使用实体框架核心2.0实现这种结构。
Word entity 字实体
public class Word
{
public Word()
{
Translations = new HashSet<Translation>();
}
[Key]
public Guid WordId { get; set; }
[Required]
public Guid LangCodeId { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage",
"CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Translation> Translations { get; set; }
}
Translation entity 翻译实体
public class Translation
{
[Key]
public Guid TranslationId { get; set; }
public Guid WordId1 { get; set; }
public Guid WordId2 { get; set; }
//[ForeignKey("WordId1,WordId2")]
public Word Words { get; set; }
}
fluent API 流利的API
modelBuilder.Entity<Translation>()
.HasOne(w => w.Words)
.WithMany(m => m.Translations)
.HasForeignKey(fk => new { fk.WordId1, fk.WordId2 });
when i try to add a migration, i get the error: 当我尝试添加迁移时,出现错误:
The relationship from 'Translation.Words' to 'Word.Translations' with
foreign key properties {'WordId1' : Guid, 'WordId2' : Guid} cannot target
the primary key {'WordId' : Guid} because it is not compatible. Configure
a principal key or a set of compatible foreign key properties for this
relationship.
I found the solution 我找到了解决方案
public partial class Translation
{
public Guid DerivedId { get; set; }
public Guid? Word1 { get; set; }
public Guid? Word2 { get; set; }
public Word Word1Navigation { get; set; }
public Word Word2Navigation { get; set; }
}
public partial class Word
{
public Word()
{
TranslationWord1Navigation = new HashSet<Translation>();
TranslationWord2Navigation = new HashSet<Translation>();
}
public Guid Id { get; set; }
public ICollection<Translation> TranslationWord1Navigation { get; set; }
public ICollection<Translation> TranslationWord2Navigation { get; set; }
}
Fluent API 流利的API
modelBuilder.Entity<Translation>(entity =>
{
entity.HasKey(e => e.DerivedId);
entity.Property(e => e.DerivedId).ValueGeneratedNever();
entity.HasOne(d => d.Word1Navigation)
.WithMany(p => p.TranslationWord1Navigation)
.HasForeignKey(d => d.Word1)
.HasConstraintName("FK__DerivedTa__Word1__5EBF139D");
entity.HasOne(d => d.Word2Navigation)
.WithMany(p => p.TranslationWord2Navigation)
.HasForeignKey(d => d.Word2)
.HasConstraintName("FK__DerivedTa__Word2__5FB337D6");
});
modelBuilder.Entity<Word>(entity =>
{
entity.Property(e => e.Id)
.HasColumnName("id")
.ValueGeneratedNever();
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.