预期类型为'System.Nullable`1 [System.Guid]',但实际值为null

问题描述 投票:0回答:1

读取属性'EMWH.UniqueAttchID'的数据库值时发生异常。预期的类型为'System.Nullable`1 [System.Guid]',但实际值为null。

我正在使用EFCore 5.0,但收到上面列出的错误。如果在我的EMWH视图中,我隐藏了UniqueAttchID中为NULL的所有记录,则可以正常工作。但是我似乎找不到一种方法来排除主键(用于关系)为NULL的记录。但是仍然可以查看所有记录。

导致错误的代码

 var workOrder = await _context.EMWHs.AsNoTracking()
                   .Include(x => x.EMWIs).ThenInclude(x => x.HQATs)
                   .Where(x => x.KeyID == WorkOrderKeyId).SingleOrDefault();

EMWH

public class EMWH
    {
        public byte EMCo { get; set; }
        public string WorkOrder { get; set; }
        public string Equipment { get; set; }
        public string? Description { get; set; }
        public Guid? UniqueAttchID { get; set; }
        [Column("udServiceRecordYN")]
        public string? ServiceRecordYN { get; set; }
        public char Complete { get; set; }
        public long KeyID { get; set; }
        [Column("DateSched")]
        [Display(Name = "Scheduled Date")]
        public  DateTime ScheduledDate { get; set; }
        public virtual EMEM EMEM { get; set; }
        public virtual  IEnumerable<EMWI> EMWIs { get; set; }
        public virtual IEnumerable<HQAT> HQATs { get; set; }
    }

HQAT

 public class HQAT
    {
        public byte HQCo { get; set; }
        public string FormName { get; set; }
        public string KeyField { get; set; }
        public string Description { get; set; }
        public string AddedBy { get; set; }
        public DateTime? AddDate { get; set; }
        public string DocName { get; set; }
        public int AttachmentID { get; set; }
        public string TableName { get; set; }
        public Guid? UniqueAttchID { get; set; }
        public string OrigFileName { get; set; }
        public string DocAttchYN { get; set; }
        public string CurrentState { get; set; }
        public int? AttachmentTypeID { get; set; }
        public string IsEmail { get; set; }
        public long KeyID { get; set; }
        public virtual udEMCD EMCD { get; set; }
        public virtual HQAF HQAF { get; set; }
        public virtual EMWH EMWH { get; set; }
        public virtual EMWI EMWI { get; set; }
        public virtual udEMED EMED { get; set; }
    }

DBContext

modelBuilder.Entity<EMWH>().ToTable("EMWH").HasKey(k=>new { k.EMCo, k.WorkOrder });
modelBuilder.Entity<HQAT>().HasOne(x => x.EMWH).WithMany(x => x.HQATs).HasForeignKey(x => x.UniqueAttchID)
            .HasPrincipalKey(x => x.UniqueAttchID);
c# sql-server linq entity-framework-core
1个回答
0
投票

您已将实体之间的键的关系设置为依靠public Guid? UniqueAttchID { get; set; },但已将其设置为可为空的GUID类型,因此在查询运行时,数据库很可能会在表中遇到空值,并且无法解决关系。简单的解决方案和最佳实践可以是使这些属性不可为空,或者使用intlong类型作为ID定义关系,因此它们不能为null,并确保您的INSERT和[C0 ]查询正确设置了关系。无论哪种方式,null都是您应该开始的地方,如果表中的记录已经包含您希望用作键的null值,那么您可以进行一些工作来弄清楚应该如何链接这些记录以及将null替换为GUID值。

© www.soinside.com 2019 - 2024. All rights reserved.