【问题标题】:Key in table becomes Guid.Empty entityframework core表中的键成为 Guid.Empty entityframework core
【发布时间】:2020-06-17 14:03:46
【问题描述】:

我有以下实体:

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; }
   }

我遇到的问题是,AccountantSubstitute 表中的 AccountantsId 变为 Guid.Empty(00000000-0000-0000-0000-000000000000),而 Accountant 表中的 AccountantsId 则按预期工作。

难道它也不能在 AccountantSubstitute 中工作吗?

【问题讨论】:

  • 您知道 Guid 在 SQL 中不是身份吗?身份是指 SQL Server 的“身份”功能,恕我直言不适用于 GUID。
  • AccountantsId 甚至被配置为外键属性?

标签: c# entity-framework .net-core entity-framework-core


【解决方案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());
    }
}

【讨论】:

    猜你喜欢
    • 2017-03-14
    • 1970-01-01
    • 2017-05-27
    • 2021-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-25
    相关资源
    最近更新 更多