【问题标题】:Unable to track an entity of type because its primary key property 'Id' is null [duplicate]无法跟踪类型实体,因为其主键属性“Id”为空 [重复]
【发布时间】: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


【解决方案1】:

您还需要传递 NotificationType 对象,因为它似乎将其值作为主键的 null。

将您的模型更改为

public class NotificationSubscription : AuditableEntity
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public string Id { get; set; }
public string UserId { get; set; }
public NotificationType NotificationTypes { get; private set; }
}

现在,设置 NotificationTypes 对象的值

context.NotificationSubscriptions.Add(new NotificationSubscription
{    
   Id = "5A4944C7-9FD8-4BC3-81F7-2ED92729962B",
   UserId = "081C459B-77D3-45F3-B26A-6879EAE53FC2",
   NotificationType= new NotificationType{
   Id=1,
   channel="Email"
 },
});

【讨论】:

  • 你能帮忙写一些代码吗?
猜你喜欢
  • 2020-03-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-02
  • 1970-01-01
  • 2020-01-31
  • 2019-12-29
  • 1970-01-01
相关资源
最近更新 更多