c# - 多对多 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; }
}
}
为简单起见,我没有使用存储库模式。
对于创建操作,有两种情况:
- 在创建联系人和地址表时填充 ContactAddress 表
- 创建联系人和地址表后填充联接表
对于我们的业务需求,我正在尝试调整第一个,因为当用户点击“保存”按钮时,用户将同时填充联系人和地址表。
我该怎么做(在创建两个实体时填充链接实体。),以及如何在更新实体时更新多对多关系?还有删除操作。
解决方案
如果您Guid Id
是在数据库级别生成的(它是在插入后分配的)。对于您的情况:插入Contact
andAddress
并链接它们,您必须先插入Contact
并Address
像这样:
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();
推荐阅读
- javascript - How can I deselect an input type='button' in JavaScript
- python - 如何最好地定位具有用户输入前缀的目录?
- html - Angular [Innerhtml] 呈现不同于 webapi 响应的静态文件
- c# - 是否可以在 intentFilter 中拦截 http://example.com/callback 重定向?
- javascript - .bootstrapMaterialDatePicker 不是 Codeigniter 3 上的函数
- silverstripe - 您如何在 silverstripe CMS 上过滤 CSV 导出?
- php - 在 move_uploaded_file 中传递根路径
- apache - .htaccess redirect if certain parameters are met
- python - 不明白为什么会出现这个浮动问题
- spring-boot - 为什么我必须禁用 Javers 的模式管理才能初始化我的应用程序?