我是 C# 新手,正在尝试使用 Postgres 设置 C# API。我的数据库由两个具有 1:1 关系的表组成。这是我的代码表格:
[Table("notification")]
public class NotificationDb
{
[Key]
public int NotificationId { get; set; }
public string Sender { get; set; } = string.Empty;
public string Recipient { get; set; } = string.Empty;
public string Subject { get; set; } = string.Empty;
public string Message { get; set; } = string.Empty;
public string Platform { get; set; } = string.Empty;
public string SendDate { get; set; } = string.Empty;
public virtual SendStatusDb? SendStatus { get; set; } = new SendStatusDb();
}
[Table("sendStatus")]
public class SendStatusDb
{
[Key]
public int SendId { get; set; }
public int Status { get; set; }
public string StatusMessage { get; set; } = string.Empty;
public int NotificationId { get; set; }
public virtual NotificationDb Notification { get; set; } = new NotificationDb();
}
为了使关系存在,我在 MailContext 中定义了它。看起来像这样:
public class MailContext: DbContext
{
public MailContext(DbContextOptions<MailContext> options): base(options) {
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<SendStatusDb>(entity =>
{
entity.HasOne(e => e.Notification)
.WithOne(e => e.SendStatus)
.HasForeignKey<SendStatusDb>(e => e.NotificationId);
});
//modelBuilder.UseSerialColumns();
}
public DbSet<NotificationDb> Notification { get; set; }
public DbSet<SendStatusDb> SendStatus { get; set; }
}
我创建了一个迁移并更新了我的数据库,到目前为止一切正常。为了进行测试,我想通过在 Swagger 中调用 GET URL 来获取数据库中的所有数据。控制器收到调用并使用 MailServiceCustom 从数据库获取所有数据。
[Route("[controller]")]
[ApiController]
public class MailController : ControllerBase
{
private readonly MailServiceCustom _mailService;
public MailController(MailContext mailContext)
{
_mailService = new MailServiceCustom(mailContext);
}
[HttpGet]
public IActionResult GetAllNotifications() {
IEnumerable<NotificationModel> notifications = _mailService.GetAllNotifications();
if (notifications.Any())
{
return Ok(notifications);
}
else
{
return NotFound();
}
}
}
public class MailServiceCustom
{
private MailContext _mailContext;
public MailServiceCustom(MailContext context)
{
_mailContext = context;
}
public List<NotificationModel> GetAllNotifications()
{
List<NotificationModel> response = new List<NotificationModel>();
var data = _mailContext.Notification.Select(x => x);
var test = data.ToList();
test.ForEach(notificationData =>
{
response.Add(new NotificationModel
{
NotificationId = notificationData.NotificationId,
Sender = notificationData.Sender,
Recipient = notificationData.Recipient,
SendDate = notificationData.SendDate,
Message = notificationData.Message,
Platform = notificationData.Platform,
});
});
return response;
}
但是当我调用
ToList()
方法时,数据库给了我一个访问冲突错误,
如果我删除表之间的关系,那么它就可以工作。但通过这种关系,我总是遇到访问冲突。
我不知道为什么会这样,但我有一个解决方案。在 SendStatus.cs 中我必须更改
public virtual NotificationDb Notification { get; set; } = new NotificationDb();
在
public NotificationDb Notification { get; set; } = null!;
然后就可以了。