簡體   English   中英

多對多 CRUD 操作 ASP.Net Core

[英]Many to Many CRUD operations ASP.Net Core

我有三個表 - 聯系人、地址和聯系人地址(連接表)。 以下是表格:

using System;
using System.Collections.Generic;

namespace ProjectWayneAPI.Models
{
public partial class Contact
{

    public Guid Id { get; set; }
    public DateTime? DateEntered { get; set; }
    public bool? Deleted { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; } 
    public string PhoneHome { get; set; }
    public string Email { get; set; }

    public virtual ICollection<ContactAddress> ContactAddress { get; set; }

}
}

using System;
using System.Collections.Generic;

namespace ProjectWayneAPI.Models
{
public partial class Address
{
    public Guid Id { get; set; }
    public DateTime? DateCreated { get; set; }
    public DateTime? DateModified { get; set; }
    public string Lot { get; set; }
    public string Road { get; set; }
    public string Street { get; set; }
    public string Suburb { get; set; }
    public string City { get; set; }
    public string State { get; set; }
    public string Postcode { get; set; }
    public string Country { get; set; }
    public string Latitude { get; set; }
    public string Longitude { get; set; }
    public bool? Deleted { get; set; }

    public virtual ICollection<ContactAddress> ContactAddress { get; set; }
}
}

using System;
using System.Collections.Generic;

namespace ProjectWayneAPI.Models
{
public partial class ContactAddress
{
    public Guid Id { get; set; }
    public DateTime? Created { get; set; }
    public bool? Deleted { get; set; }
    public Guid? ContactId { get; set; }
    public Guid? AddressId { get; set; }

    public virtual Address Address { get; set; }
    public virtual Contact Contact { get; set; }
}
}

為簡單起見,我沒有使用存儲庫模式。

對於創建操作,有兩種情況:

  • 在創建聯系人和地址表時填充 ContactAddress 表
  • 在創建聯系人和地址表后填充連接表

對於我們的業務需求,我正在嘗試調整第一個,因為用戶將在用戶點擊“保存”按鈕時同時填充聯系人和地址表。

我該怎么做(在創建兩個實體時填充鏈接實體。),以及如何在更新實體時更新多對多關系? 還有刪除操作。

如果您的Guid Id是在數據庫級別生成的(它是在插入后分配的)。 對於您的情況:插入ContactAddress並鏈接它們,您必須先像這樣插入ContactAddress

var contact = new Contact(); 
var address = new Address();  

dbContext.Add(contact);
dbContext.Add(address);

dbContext.SaveChanges();

var contactAddress = new ContactAddress() 
{
   AddressId = address.Id,
   ContactId = contact.Id 
}
dbContext.Add(contactAddress);
dbContext.SaveChanges();

暫無
暫無

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

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