iT邦幫忙

2024 iThome 鐵人賽

DAY 19
0
Modern Web

從零開始教你做AspNet7.0購物網站系列 第 19

Day-19 Asp.Net Cord常用資料庫關聯

  • 分享至 

  • xImage
  •  

接下來要設置資料庫關聯

一對一關聯

假設一張User表的model長這樣

public partial class User
{
    public int Id { get; set; }

    public string? name { get; set; }

    public string password { get; set; }

    public int adress_id { get; set; }
    public Adress Adress { get; set; }

}

還有一張Adress表長這樣

public partial class Adress
{
    public int Id { get; set; }

    public string? name { get; set; }

    public User User { get; set; }

}

然後資料庫上下文的OnModelCreating方法就要新增一段

modelBuilder.Entity<User>()
    .HasOne(p => p.Adress)
    .WithOne(pc => pc.User)
    .HasForeignKey<User>(p => p.adress_id);

這樣子就是一個一對一連接,由User的adress_id欄位對應Adress表的id欄位

一對多關聯

User表的model

public partial class User
{
    public int Id { get; set; }

    public string? name { get; set; }

    public string password { get; set; }

    public int adress_id { get; set; }
    public ICollection<Adress> Adress { get; set; }

}

Adress表的Model

public partial class Adress
{
    public int Id { get; set; }

    public string? name { get; set; }

    public User User { get; set; }

}

然後資料庫上下文的OnModelCreating方法就要新增一段

modelBuilder.Entity<User>()
    .HasMany(p => p.Adress)
    .WithOne(pc => pc.User)
    .HasForeignKey(p => p.adress_id);

多對多關聯

User表的model

public partial class User
{
    public int Id { get; set; }

    public string? Name { get; set; }

    public string Password { get; set; }

    public ICollection<UserAddress> UserAddresses { get; set; }
}

Adress表的Model

public partial class Address
{
    public int Id { get; set; }

    public string? Name { get; set; }

    public ICollection<UserAddress> UserAddresses { get; set; }
}

多對多關聯需要一張中間表,所以我們新增一張中間表UserAddress

public class UserAddress
{
    public int UserId { get; set; }
    public User User { get; set; }

    public int AddressId { get; set; }
    public Address Address { get; set; }
}

然後資料庫上下文要設定三個

modelBuilder.Entity<UserAddress>()
    .HasKey(ua => new { ua.UserId, ua.AddressId });

modelBuilder.Entity<UserAddress>()
    .HasOne(ua => ua.User)
    .WithMany(u => u.UserAddresses)
    .HasForeignKey(ua => ua.UserId);

modelBuilder.Entity<UserAddress>()
    .HasOne(ua => ua.Address)
    .WithMany(a => a.UserAddresses)
    .HasForeignKey(ua => ua.AddressId);

上面的資料庫關聯設定好之後,記得在下一次前面用過的新增資料庫遷移檔案和更新資料庫的指令,把資料庫更新喔!


上一篇
Day-18 Asp.Net Core常用資料庫查詢語法介紹
下一篇
Day-20 MD5加密介紹
系列文
從零開始教你做AspNet7.0購物網站30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言