我使用.NET Core最終實體框架核心在兩個實體之間建立多對多關係。我已經建立了連接實體滿足要關係,基於陰影屬性的主鍵是這樣的:以多對多關係作爲影子屬性的複合主鍵
實體用戶:
public class User
{
[Key]
public int IDUser { get; set; }
[Required]
public string Forename { get; set; }
public List<UserGroup> UsersGroups { get; set; }
}
實體組:
public class Group
{
[Key]
public int IDGroup { get; set; }
[Required]
public string GroupName { get; set; }
public List<UserGroup> UsersGroups { get; set; }
}
實體用戶組:
public class UserGroup
{
public Group Group { get; set; }
public User User { get; set; }
}
DB上下文類別:
public class DBContext : DbContext
{
public DBContext(DbContextOptions<DBContext> options)
: base(options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
// shadow property - primary/foreign key
modelBuilder.Entity<UserGroup>()
.Property<int>("IDUser");
// shadow property - primary/foreign key
modelBuilder.Entity<UserGroup>()
.Property<int>("IDGroup");
// composite primary key based on shadow properties
modelBuilder.Entity<UserGroup>()
.HasKey(new string[]{ "IDUser", "IDGroup" });
modelBuilder.Entity<UserGroup>()
.HasOne(ug => ug.Group)
.WithMany(g => g.UsersGroups)
.HasForeignKey(???); //what to do here ?
modelBuilder.Entity<UserGroup>()
.HasOne(ug => ug.User)
.WithMany(u => u.UsersGroups)
.HasForeignKey(???); // what to do here ?
base.OnModelCreating(modelBuilder);
}
public DbSet<Group> Groups { get; set; }
public DbSet<User> Users { get; set; }
public DbSet<UserGroup> UserGroups { get; set; }
}
現在。我如何根據我的影子組合主鍵在UserGroup實體上正確建立外鍵?我希望這個陰影主鍵同時是外鍵。我現在不知道如何引用這個陰影主鍵來創建外鍵。我標記了我不知道如何處理問號。
不知道你的意思是使複合PK爲FK。 FK是指向* principal *(引用)表的PK的屬性(陰影或不)。在你的情況下,你應該分別使用''IDGroup「'和''IDUser」'代替''''。 –
https://docs.microsoft.com/en-us/ef/core/modeling/relationships 本文的最後一節(多對多)。存在具有顯式外鍵(PostId,TagID)的連接實體'PostTag',它們是同時是主鍵(在'OnMOdelCreating'方法中的流暢API中建立的)。我只想得到與陰影屬性相同的效果。 –
它們只是用流利的API建立的複合PK的**部分**。您已經定義了具有陰影屬性的複合PK,因此您現在只需將該鍵的各個部分映射爲FK。你是否嘗試了我在之前的評論結尾處寫的內容? –