【问题标题】:I get error: Value cannot be null, Why is my ICollection always null?我收到错误:值不能为空,为什么我的 ICollection 始终为空?
【发布时间】:2019-10-31 12:35:18
【问题描述】:

这是组织照片模块

public class OrganizationPhoto
{
    public int Id { get; set; }
    public string Url { get; set; }
    public string Description { get; set; }
    public DateTime DateAdded { get; set; }
    public bool IsMain { get; set; }
    public string PublicID { get; set; }
    public Organization Organization { get; set; }
    public int OrganizationId { get; set; }
}

这是组织模块

public class Organization
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public DateTime DateCreated { get; set; }
    public string PublicID { get; set; }
    public User User { get; set; }
    public int UserId { get; set; }
    public ICollection<OrganizationPhoto> OrganizationPhotos { get; set; }
    public ICollection<OrganizationHeadPhoto> OrganizationHeadPhotos { get; set; }
}

我用 dtos 在 automapper 中映射 OrganizationPhoto

        CreateMap<OrganizationPhoto, PhotosForDetailedDto>();
        CreateMap<OrganizationPhoto, PhotoForReturnDto>();
        CreateMap<PhotoForCreationDto, OrganizationPhoto>();

然后我像这样通过 id 获取组织:

Task<Organization> GetOrganizationById(int id);

    public async Task<Organization> GetOrganizationById(int id)
    {
        var organization = await _context.Organizations.FirstOrDefaultAsync(p => p.Id == id);
        return organization;
    }

然后我尝试从 ICollection OrganizationPhotos 获取值,但它为空 see image

【问题讨论】:

  • 我猜你需要包括他们:Loading Related Data
  • 你已经在类的构造函数中初始化了它。

标签: c# asp.net asp.net-core entity-framework-core


【解决方案1】:

默认情况下,EF 从不加载相关实体。您必须急切地或显式地加载关系,或者设置延迟加载。最好的方法是预先加载,因为它会在一个查询中使用适当的连接完成所有操作:

 var organization = await _context.Organizations
     .Include(x => x.OrganizationPhotos)
     .Include(x => x.OrganizationHeadPhotos)
     .FirstOrDefaultAsync(p => p.Id == id);

如果您还需要加载子关系,您可能还需要使用ThenInclude

.Include(x => x.OrganizationPhotos)
    .ThenInclude(x => x.SomeOtherRelationship)

你应该避免延迟加载,因为它太容易破坏你的数据库,如果你不注意你在做什么,但是如果你希望它们“自动”加载,那么你首先需要制作属性虚拟:

public virtual ICollection<OrganizationPhoto> OrganizationPhotos { get; set; }

然后通过以下方式启用延迟加载:

services.AddDbContext<MyContext>(o =>
    o.UseSqlServer(Configuration.GetConnectionString("Foo"))
     .UseLazyLoadingProxies());

【讨论】:

    猜你喜欢
    • 2021-12-30
    • 1970-01-01
    • 1970-01-01
    • 2016-04-05
    • 1970-01-01
    • 1970-01-01
    • 2021-11-11
    • 2021-03-02
    • 2013-04-07
    相关资源
    最近更新 更多