簡體   English   中英

實體框架數據建模:2個外鍵和一個主鍵

[英]Entity Framework data modelling: 2 foreign keys and a primary key

我有以下表格:

public class Event {
  public int Id {get;set;}
}

public class Participant{
  public int Id {get;set;}
}

public class Registration{
  public int Id {get;set;}
  public int EventId {get;set;}
  public int PaticipantId {get;set;}
}

我將注冊ID作為主鍵,但是如何確保eventid和particpantid是唯一的? 我已經考慮過復合鍵,但是我需要在注冊時使用Id屬性,因為我需要將其作為另一個類/表上的外鍵。

對於任何對我的dbcontext感到好奇的人,它是這樣的:

modelBuilder.Entity<Registration>()
                .HasRequired(e => e.Participant)
                .WithMany(u => u.Events)
                .HasForeignKey(e => e.ParticipantId);

            modelBuilder.Entity<Registration>()
                .HasRequired(e => e.Event)
                .WithMany(u => u.Participants)
                .HasForeignKey(e => e.EventId);

創建另一個包含EventId和PaticipantId作為復合鍵的表,然后將該表ID放入您的Registration表中。

public class Event {
  public int Id {get;set;}
}

public class Participant{
  public int Id {get;set;}
}

public class NewTable{
   public int Id {get;set;}
   public int EventId  {get;set;}
   public int PaticipantId {get;set;}
}

public class Registration{
  public int Id {get;set;}
  public int NewTableId {get;set;}
}

實際上,有很多方法可以確保EventId和PaticipantId的組合是唯一的,甚至可以不接觸模型。

可以在您的數據庫中設置它:您可以聲明兩個字段UNIQUE的組合,然后在應用程序中捕獲錯誤並根據需要進行處理。

您還可以使用檢查組合是否存在的函數直接在應用程序內部進行驗證。 (如果存在,則返回false)

您還可以在模型中添加ANOTHER字段,該字符串代表相同字段中的兩個ID,並聲明其唯一性

實際上,有很多解決方案可以解決您的問題...選擇對自己更輕松的解決方案。

您應該在EventId和ParticipantId列的組合上添加唯一鍵

由於您正在使用EF遷移,因此可以將唯一鍵添加到模型中,然后讓Entity Framework為您生成新的遷移。 然后,此遷移將向數據庫添加唯一密鑰。 取決於您的實體框架版本,這將有所不同。

在Entity Framework Core 1.0.0中,這很簡單:

modelBuilder.Entity<Registration>().HasIndex(x => new { x.ParticipantId, x.EventId}).IsUnique();

使用Entity Framework 6時,可以使用批注或流利的api(盡管很冗長):

帶有注釋:

public class Registration
{
  public int Id {get;set;}
  [Index("UQ_Registration_EventId_ParticipantId", 1, IsUnique = true)]
  public int EventId {get;set;}
  [Index("UQ_Registration_EventId_ParticipantId", 2, IsUnique = true)]
  public int PaticipantId {get;set;}
}

或使用流暢的API:

string uniqueIndex = "UQ_Registration_EventId_ParticipantId";

modelBuilder.Entity<Registration>().Property(t => t.EventId)
    .HasColumnAnnotation(
        IndexAnnotation.AnnotationName,
        new IndexAnnotation(
            new IndexAttribute(uniqueIndex)
            {
                IsUnique = true,
                Order = 1
            }
        )
    );

modelBuilder.Entity<Registration>().Property(t => t.ParticipantId)
    .HasColumnAnnotation(
        IndexAnnotation.AnnotationName,
        new IndexAnnotation(
            new IndexAttribute(uniqueIndex)
            {
                IsUnique = true,
                Order = 2
            }
        )
    );

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM