簡體   English   中英

在引用身份用戶表的實體框架核心中的表上創建外鍵

[英]Create a foreign key on a table in entity framework core that references the identity user table

我正在嘗試創建從 AspNet Identity 自動生成的 AspNetUsers 表到我自己創建的表的關系。 前任。 表 A 的 UserId 列設置為 nvarchar(128),我希望它與 AspNet Users 表的 UserId 列相關。 這是一個 Asp.Net MVC web 應用程序。

首先我有一些考慮你不應該使用 nvarchar 作為 FK 更不用說 UserId 因為它對於像 SQL 這樣的結構數據庫索引更高效但是如果你使用非結構忽略這個......

現在對於您的解決方案來說很好,請參閱表之間的關系必須通過 ConfigMap 完成,其中 entityFramework 了解對象之間的關系,並將它們 map 到數據庫我會給你一個例子:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    // Configure StudentId as FK for StudentAddress
    modelBuilder.Entity<Student>()
                .HasRequired(s => s.Address) 
                .WithRequiredPrincipal(ad => ad.Student); 

}

將這些類視為關系對象

public class Student
{
    public int StudentId { get; set; }
    public string StudentName { get; set; }

    public virtual StudentAddress Address { get; set; }
}
     
public class StudentAddress 
{
    [ForeignKey("Student")]
    public int StudentAddressId { get; set; }
        
    public string Address1 { get; set; }
    public string Address2 { get; set; }
    public string City { get; set; }
    public int Zipcode { get; set; }
    public string State { get; set; }
    public string Country { get; set; }

    public virtual Student Student { get; set; }
}

看到關系應該如何發生的映射是在這里完成的 OnModelCreating

還有另一種方法可以通過為數據庫中的每個對象/表進行配置 class 來做到這一點,這樣它會更有條理

class CustomerConfiguration : IEntityTypeConfiguration<Customer>
{
  public void Configure(EntityTypeBuilder<Customer> builder)
  {
     builder.HasKey(c => c.AlternateKey);
     builder.Property(c => c.Name).HasMaxLength(200);
   }
}

示例: EF Core 映射 EntityTypeConfiguration

我也可以把entityFramework文檔作為它開發的一個很好的指南 1:1 https://www.entityframeworktutorial.net/code-first/configure-one-to-one-relationship-in-code-first.aspx

1:N https://www.entityframeworktutorial.net/code-first/configure-one-to-many-relationship-in-code-first.aspx

N:N https://www.entityframeworktutorial.net/code-first/configure-many-to-many-relationship-in-code-first.aspx

我真的希望我能幫助你解決問題。

另一點沒有評論,但你應該研究遷移並在你的項目中使用它們來控制你在數據庫中的更改

https://www.entityframeworktutorial.net/efcore/entity-framework-core-migration.aspx#:~:text=Migration%20is%20a%20way%20to,on%20the%20EF%20Core%20model

暫無
暫無

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

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