首页 > 解决方案 > 多对多 CRUD 操作 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; }
}
}

为简单起见,我没有使用存储库模式。

对于创建操作,有两种情况:

对于我们的业务需求,我正在尝试调整第一个,因为当用户点击“保存”按钮时,用户将同时填充联系人和地址表。

我该怎么做(在创建两个实体时填充链接实体。),以及如何在更新实体时更新多对多关系?还有删除操作。

标签: c#linqasp.net-coreasp.net-core-webapief-core-3.0

解决方案


如果您Guid Id是在数据库级别生成的(它是在插入后分配的)。对于您的情况:插入ContactandAddress并链接它们,您必须先插入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();


推荐阅读