我有兩節這樣的課。
public class Client { public Guid Id { get; set; } ... }
public class Meeting
{
public Guid Id { get; set; }
public Client[] Invitees { get; set; } = new Client[0];
public Client[] Attendees { get; set; } = new Client[0];
}
背景關系中的配置如下。
private static void OnModelCreating(EntityTypeBuilder<Client> entity) { }
private static void OnModelCreating(EntityTypeBuilder<Meeting> entity)
{
entity.HasMany(a => a.Invitees);
entity.HasMany(a => a.Attendees);
}
我只需要從我的會議中參考客戶。客戶不需要知道任何事情。會議需要提及客戶兩次或更少(自愿出席,可選邀請)。
上面的遷移創建了兩個表,我很滿意。但它也創建了兩個索引,就像這樣。
migrationBuilder.CreateIndex(
name: "IX_Clients_MeetingId",
table: "Clients",
column: "MeetingId");
migrationBuilder.CreateIndex(
name: "IX_Clients_MeetingId1",
table: "Clients",
column: "MeetingId1");
我不喜歡那個。首先,我預計只創建一個索引,因為我們正在索引 sme 表的主鍵。其次,如果我不能回避,我不喜歡IX_Clients_MeetingId1.
- 我可以做什么(如果有的話)只創建一個索引?
- How can I specify the name of the index if I'm not using
WithMany()?
I'm not providing any links as a proof of effort. Checking MSDN, SO and blogs resulted in a lot of hits on the full M2M relation, i.e. .HasMany(...).WithMany(...) and that's not what I'm heading for. I saw a suggestion to manually make the change in the migration file but tempering with those is begging for issues later. I'm not sure how to google-off the irrelevant results and I'm starting to fear that the "half" M2M I'm attempting is a bad idea (there's no in-between table created, for instance).
uj5u.com熱心網友回復:
好吧,EF 似乎假設您有 2 個 one2many 關系。所以一個客戶最多只能被邀請參加一次會議。
作為快速解決方案,您可以
- 顯式添加 2 個連接物體并配置適當的 one2many 關系。然后你有一張邀請表和一張出勤表。
- 添加一個多對多連接物體,它也跟蹤鏈接型別(客戶端、會議、鏈接型別),以便“邀請”和“參與”是鏈接型別
- 向客戶端添加 2 個屬性以向 EF 顯示您的意思是多對多關系:
像這樣:
public class Client {
public Guid Id { get; set; }
public ICollection<Meeting> InvitedTo { get; set; }
public ICollection<Meeting> Attended { get; set; }
}
這些不應顯示在客戶端表中,而是顯示為 2 個單獨的表。(本質上是帶有隱式連接物體的解決方案1)
uj5u.com熱心網友回復:
退一步說,我認為您可以通過引入MeetingMember物體來簡單地改進模型。在當前模型中,客戶無法被邀請參加兩次會議,客戶也不會被限制參加他們被邀請參加的會議。所以你需要一個 M2M 關系,如果你使用一個顯式鏈接物體,你可以逃脫,比如
MeetingMember(MeetingId, ClientId, InvitedAt, Attended)
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/359178.html
標籤:c# entity-framework many-to-many entity-framework-migrations asp.net-core-5.0
上一篇:在物體框架中更新物體時執行操作
