EF6延迟加载不起作用

时间:2017-03-14 10:34:27

标签: c# entity-framework generics

我有这些对象:

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

如您所见,我有一个通用存储库。只使用一个对象,它可以正常工作,但导航属性不行。使用延迟加载时,它找不到导航属性(在本例中为域)。我收到这个错误:

  

&#39; ObjectContent`1&#39;类型无法序列化响应正文   内容类型&#39; application / json;字符集= UTF-8&#39;

当我尝试将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()
        };
    }

1 个答案:

答案 0 :(得分:1)

因为您的上下文包含在using语句中,所以延迟加载将永远不会起作用,因为当您离开GetAll()方法时,上下文已被处理并且与数据库的连接已被删除闭合。

尽管延迟加载看起来是一个很好的选择,我强烈建议不要使用它,除非你知道你在做什么。显式加载所需的数据要安全得多。

相关问题