【发布时间】:2021-08-27 05:04:50
【问题描述】:
我有两个这样的表:
public class NotificationType : AuditableEntity
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public string Id { get; set; }
public string Channel { get; set; }
}
public class NotificationSubscription : AuditableEntity
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public string Id { get; set; }
public string UserId { get; set; }
public string NotificationTypeId { get; set; }
public NotificationType NotificationTypes { get; private set; } = new();
}
当我播种数据时,我会这样做:
context.NotificationTypes.Add(new NotificationType
{
Id = "4C1B3788-3CDE-4F6D-82EB-7B4B71A601EF",
Channel = "Email",
});
await context.SaveChangesAsync();
context.NotificationSubscriptions.Add(new NotificationSubscription
{
Id = "5A4944C7-9FD8-4BC3-81F7-2ED92729962B",
UserId = "081C459B-77D3-45F3-B26A-6879EAE53FC2",
NotificationTypeId = "4C1B3788-3CDE-4F6D-82EB-7B4B71A601EF",
});
await context.SaveChangesAsync();
DbContext
public DbSet<NotificationType> NotificationTypes { get; set; }
public DbSet<NotificationSubscription> NotificationSubscriptions { get; set; }
public override async Task<int> SaveChangesAsync(CancellationToken cancellationToken = new CancellationToken())
{
foreach (Microsoft.EntityFrameworkCore.ChangeTracking.EntityEntry<AuditableEntity> entry in ChangeTracker.Entries<AuditableEntity>())
{
switch (entry.State)
{
case EntityState.Added:
entry.Entity.CreatedBy = _currentUserService.UserId;
entry.Entity.Created = _dateTime.Now;
break;
case EntityState.Modified:
entry.Entity.LastModifiedBy = _currentUserService.UserId;
entry.Entity.LastModified = _dateTime.Now;
break;
}
}
var result = await base.SaveChangesAsync(cancellationToken);
return result;
}
NotificationTypes 保存时没有任何问题,但在尝试保存到 NotificationSubscriptions 时,出现错误:
无法跟踪“NotificationType”类型的实体,因为它 主键属性“Id”为空。
我猜这个问题是由于一对一关系的映射造成的。但我不知道如何准确解决这些问题。我不想在添加 NotificationTypes 时添加 NotificationType,我只想用 NotificationTypeId 引用它。
请指导我解决方法或可能的解决方案。
【问题讨论】:
-
(小注:您的 id 看起来非常像 GUID。有一个原生的
Guid-datatype 比字符串更适合处理这些 - 原因很明显)您能否提供 complete 保存这些实体的代码,以便我们可以看到它们之间的关系以及何时提交任何更改? -
在大多数情况下,最好使用对象而不是 Id。所以不要分配 NotificationTypeId 而是 NotificationType
-
@FranzGleichmann 是的,ID 是
Guid,我也更新了代码以显示 DbContext。那是我的 DbContext 中唯一的事情。我在模型生成器中没有配置。 -
@Klamsi
don't assign the NotificationTypeId but NotificationType是的,我想这样做。但我该怎么办? -
因为问题是由您正在初始化 reference navigation property 引起的。链接帖子的答案解释了为什么你不应该这样做。如果仍然不清楚,问题是
= new();。删除它,问题就消失了。
标签: c# entity-framework-core asp.net-core-5.0