EF7一對一的關係


我正在努力處理新的EF7,並且在處理一對一關係時遇到了奇怪的行為。

我有以下型號

public class Material
{
    [Key]
    [Required]
    [Column(TypeName = "bigint")]
    public long Id { get; set; }

    [Required]
    [MaxLength(128)]
    public string Name { get; set; }

    [Required]
    [MaxLength(512)]
    public string Description { get; set; }

    [Required]
    [Column(TypeName = "money")]
    public decimal CostPerUnit { get; set; }

    public virtual Unit UnitOfMeasure { get; set; }

    [Required]
    [Column(TypeName = "bit")]
    public bool IsActive { get; set; } = false;
}


public class Unit
{
    [Key]
    [Column(TypeName = "bigint")]
    public long Id { get; set; }

    [Required]
    [MaxLength(32)]
    public string Name { get; set; }

    [Required]
    [MaxLength(64)]
    public string Description { get; set; }

    [Required]
    public string Type { get; set; }
}

我正在構建表格如下:

public class Material
{
    [Key]
    [Required]
    [Column(TypeName = "bigint")]
    public long Id { get; set; }

    [Required]
    [MaxLength(128)]
    public string Name { get; set; }

    [Required]
    [MaxLength(512)]
    public string Description { get; set; }

    [Required]
    [Column(TypeName = "money")]
    public decimal CostPerUnit { get; set; }

    public virtual Unit UnitOfMeasure { get; set; }

    [Required]
    [Column(TypeName = "bit")]
    public bool IsActive { get; set; } = false;
}


public class Unit
{
    [Key]
    [Column(TypeName = "bigint")]
    public long Id { get; set; }

    [Required]
    [MaxLength(32)]
    public string Name { get; set; }

    [Required]
    [MaxLength(64)]
    public string Description { get; set; }

    [Required]
    public string Type { get; set; }
}

我現在遇到的問題是,當我嘗試查詢具有度量單位的材料時,度量單位始終設置為null,但是當我檢查生成的表時,我可以清楚地看到外鍵是實際創建。

我也嘗試在OnModel中強制創建關係但是我仍然無法檢索單元對象。

public class Material
{
    [Key]
    [Required]
    [Column(TypeName = "bigint")]
    public long Id { get; set; }

    [Required]
    [MaxLength(128)]
    public string Name { get; set; }

    [Required]
    [MaxLength(512)]
    public string Description { get; set; }

    [Required]
    [Column(TypeName = "money")]
    public decimal CostPerUnit { get; set; }

    public virtual Unit UnitOfMeasure { get; set; }

    [Required]
    [Column(TypeName = "bit")]
    public bool IsActive { get; set; } = false;
}


public class Unit
{
    [Key]
    [Column(TypeName = "bigint")]
    public long Id { get; set; }

    [Required]
    [MaxLength(32)]
    public string Name { get; set; }

    [Required]
    [MaxLength(64)]
    public string Description { get; set; }

    [Required]
    public string Type { get; set; }
}

我應該如何添加此引用或者甚至支持這個?

一般承認的答案

您是如何獲得參考的?此時延遲加載在EF7中不起作用。你必須進行急切加載(dbContext.Materials.Include(m => m.UnitOfMeasure))或其顯式版本。





許可下: CC-BY-SA
不隸屬於 Stack Overflow
這個KB合法嗎? 是的,了解原因