提问者:小点点

表中的键变为GUID.Empty


我有以下实体:

public class ElectedRepresentativeData : TimeTrackBase
{
    [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public Guid Id { get; set; }

        public int CustomerNumber { get; set; }

        public int RegionId { get; set; }

        public bool Success { get; set; }
        public virtual Accountants Accountants { get; set; }
}

public class Accountants : TimeTrackBase
{
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public Guid Id { get; set; }
        public Guid ElectedRepresentativeDataId { get; set; }
        public virtual Accountant Accountant { get; set; }
        public virtual AccountantSubstitute AccountantSubstitute { get; set; }
}
    public class Accountant : TimeTrackBase
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public Guid Id { get; set; }
        public Guid AccountantsId { get; set; }
        public virtual Person AccountantPerson { get; set; }
    }

   public class AccountantSubstitute : TimeTrackBase
   {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public Guid Id { get; set; }
        public Guid AccountantsId { get; set; }
        public virtual Person AccountantPerson { get; set; }
   }

我遇到的问题是,AccountantsId在表AccountantSubstitute中变为GUID.Empty(00000000-0000-0000-000000000000),而表AccountantsId在表AccountantsId中的工作方式与预期相同。

它不应该也在AccountantSubstitution中工作吗?


共1个答案

匿名用户

您必须创建一个配置类,并更详细地配置属性。

   public class AccountantConfiguration : IEntityTypeConfiguration<Accountant>
    {
        /// <inheritdoc />
        public void Configure(EntityTypeBuilder<Communication> builder)
        {
            if (builder == null)
                return;

            builder.ToTable("Accountant");

            builder.HasKey(k => new {Id = k.Id});

            builder.Property(p => p.Id)
                .IsRequired();

            builder.Property(p => p.AccountantsId)
                .IsRequired()
                .HasDefaultValueSql("newid()")
                .ValueGeneratedOnAdd();

            ...

        }
    }

并在DbContext类中添加此配置

public sealed class Context : DbContext
{

    ...

    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);

        if (builder == null) 
            return;

        builder.ApplyConfiguration(new AccountantConfiguration());
    }
}