簡體   English   中英

Entity Framework Core 中 Fluent API 中的關系

[英]Relationship in Fluent API in Entity Framework Core

我需要在共享字符串類型的公共列的兩個表之間創建關系 - 我該怎么做?

這就是我所做的。 這行得通嗎?

您需要指定外鍵(最好總是)和主鍵(如果它與主鍵不同)。 為了使用主鍵以外的主鍵,您需要創建一個唯一約束。 在 EF 中,您可以通過指定 HasIndex 和 IsUnique 來執行此操作,否則您將收到錯誤消息,因為所選主鍵不是唯一列。

看這個例子:

//HaweyTajer is the principal table
modelbuilder.Entity<HaweyTajer>(entity => 
{
   //Mark the primary key
   entity.HasKey(x => x.Id);

   //Build the relation (Consider adding OnDelete())
   entity.HasMany(x => x.Certivicates)
         .WithOne(x => x.HaweyTaker)
         .HasPrincipalKey(x => x.AZbaraNum)
         .HasForeignKey(x => x.AZbaraNum);

   //Build the index on the column inside the principal table
   entity.HasIndex(x => x.AZbaraNum)
         .IsUnique();
   
});

您不妨將列類型更改為不是 nvarchar(250) 而不是 null 或使用 HasFilter() 向索引添加過濾器。

參考: https://learn.microsoft.com/en-us/ef/ef6/modeling/code-first/fluent/relationships

希望這可以幫助。

暫無
暫無

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

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