导航属性不是延迟加载EF6 Code First

时间:2018-04-03 03:26:16

标签: c# asp.net entity-framework asp.net-web-api

我已经搜索过网络并堆叠溢出以寻找我的问题的答案,但我没有运气。

基本上我有一个模型,它有2个相同对象和其他对象的引用。当我向模型插入记录时,属性未加载,因此我尝试了Context.Attach函数没有运气。我还尝试查询现有记录,但对象仍未附加

这是我的模特

  [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    [Key]
    public Guid TripID { get; set; }
    [Required]
    [Range(1, 999999, ErrorMessage = "Total Distance can only be a positive number non-zero")]
    public double TotalDistance { get; set; }

    [Required]
    public double AmountDue { get; set; }
    [Required]
    public TripPaymentType PaymentType { get; set; }
    [Required]
    public TripStatus CurrentStatus { get; set; }
    [ForeignKey("TripTypeId")]
    public TripType TripType { get; set; }
    [Required]
    public Guid TripTypeId { get; set; }
    [Required]
    public DateTime TransactionDate { get; set; }
    [Required]
    public Guid CustomerID { get; set; }
    [ForeignKey("CustomerID")]
    public UserInfo Customer { get; set; }
    public Guid? DriverID { get; set; }
    [ForeignKey("DriverID")]
    public UserInfo Driver { get; set; }

配置单个对象多个引用

             modelBuilder.Entity<TripHistory>()
            .HasRequired(th => th.Customer)
            .WithMany()
            .WillCascadeOnDelete(false);
        modelBuilder.Entity<TripHistory>()
            .HasOptional(th => th.Driver)
            .WithMany()
            .WillCascadeOnDelete(false);

非常感谢任何帮助

1 个答案:

答案 0 :(得分:0)

供将来参考,

出于某种原因,即使通过使用.Include()方法启用延迟加载,我也必须强制加载对象。