簡體   English   中英

EF6延遲加載不起作用

[英]EF6 lazy loading not working

我有這些對象:

public class Domain : EntityTypeConfiguration<Domain>, IEntity
{
    [Key]
    public int Id { get; set; }

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

    public Guid Guid { get; set; }

    public ICollection<Website> Websites { get; set; }
}

public class Website: EntityTypeConfiguration<Website>, IEntity
{
    [Key]
    public int Id { get; set; }

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

    [Range(1, int.MaxValue)]
    public int DomainId { get; set; }

    public string Description { get; set; }

    [DatabaseGenerated(DatabaseGeneratedOption.Computed)]

    public DateTime CreationDate { get; set; }

    [Required]
    public Guid Guid { get; set; }

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

    public bool AllowToSharedTemplates { get; set; }

    public int PublishWebsiteId { get; set; }

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

    public virtual Domain Domain { get; set; }
}

當我需要所有網站時,我也需要連接的域(每個網站都有一個域)。 但是,這不起作用。

    public IList<T> GetAll()
    {
        IList<T> ret;

        using (IocDbContext db = Context.CreateContext())
        {
            DbSet<T> dbSet = db.Set<T>();
            ret = dbSet.ToList();
        }

        return ret;
    }

CreateContext

    public IocDbContext CreateContext()
    {
        IocDbContext rety=  new IocDbContext(_siteType.ConnectionString);
        rety.Configuration.ProxyCreationEnabled = true;

        return rety;
    }

如您所見,我有一個通用存儲庫。 它僅對一個對象有效,但對導航屬性無效。 對於延遲加載,它將找不到導航屬性(在這種情況下為domain)。 我收到此錯誤:

'ObjectContent`1'類型未能序列化內容類型'application / json的響應主體; charset = utf-8'。

當我嘗試將DTO映射到對象時:

public static Objects.Website ToModel(this Data.Contexts.Website value)
    {
        if (value == null)
            return null;

        return new Website
        {
            Id = value.Id,
            Name = value.Name,
            Domain = value.Domain?.ToModel()
        };
    }

因為您將上下文包裝在using語句中,所以延遲加載將永遠無法進行,因為到您離開GetAll()方法時,上下文已被處置,並且與數據庫的連接已關閉。

盡管延遲加載看起來是一個不錯的選擇,但我強烈建議您不要使用它,除非您知道自己在做什么。 顯式加載所需數據要安全得多。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM