繁体   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