【问题标题】:Reference of related entity is gone after creating the record创建记录后相关实体的引用消失了
【发布时间】:2019-11-26 00:50:15
【问题描述】:

我正在使用实体框架编写一个简单的 .net 核心应用程序。我有一种情况,保存记录后相关实体的引用为空。请参阅下面的代码和屏幕截图以了解更多信息。

正如您在下图中所见,引用是使用组织实体创建的。

但是当我从上下文中获取所有列表时,引用就消失了。

组织实体

public class Organization
{
    public Organization()
    {
        this.Listings = new List<Listing>();
        this.ContactRoles = new List<ContactRole>();
    }

    [Key]
    public int Id { get; set; }
    public string OrgName { get; set; }
    public string OrgWebsite { get; set; }
    public string OrgMissionStatement { get; set; }
    public string OrgOwner { get; set; }
    public string OrgDescription { get; set; }
    public bool IsVerified { get; set; }

    public string Address1 { get; set; }
    public string Address2 { get; set; }
    public string City { get; set; }
    public int Zipcode { get; set; }
    //public string Country { get; set; }

    //ForeignKey
    [ForeignKey("Contact")]
    public int ContactId { get; set; }
    public virtual Contact Contact { get; set; }

    public virtual List<ContactRole> ContactRoles { get; set; }
    public virtual List<Listing> Listings { get; set; }
}

上市实体

[Table("Listing")]
    public class Listing
    {
        [Key]
        public int Id { get; set; }

        public string ListingTitle { get; set; }
        public string ListingDescription { get; set; }

        [ForeignKey("Organization")]
        public int OrgId { get; set; }
        public virtual Organization Organization { get; set; }
    }

控制器

    public IEnumerable<Listing> GetAll()
    {
        return _context.Listings;
    }

    public Listing GetById(int id)
    {
        return _context.Listings.Find(id);
    }

    public Listing Create(Listing listing)
    {
        try
        {
            var org = _context.Organizations.SingleOrDefault(x => x.Id == listing.OrgId);
            org.Listings.Add(listing);

            _context.Listings.Add(listing);

            _context.SaveChanges();

            return listing;
        }
        catch (Exception ex)
        {

            throw ex;
        }
    }

目前我在 Linq 中使用 Include 来获取相关实体,但我需要所有相关实体而不使用 Include。

【问题讨论】:

  • 我对图像感到困惑。您能否以可读的方式提供您使用过的代码,以便我看一下?另外,您说您正在使用 Include 来获取相关实体,但是您需要在不使用 Include 的情况下获取所有相关实体 - 这就是 Include 的全部意义,除非您编写单独的查询以从每个 DbSet 中获取每个查询,否则您无法做到这一点跨度>
  • 我更新了代码部分,希望现在有一些意义。当我使用 Include 时,只需要知道为什么当我获得列表时它变为 null 的问题。
  • 问题可以简化为一种方法:GetAll() + 类。其余的(包括屏幕转储)无关紧要。您从数据库中获取列表,并且它们没有填充参考。就这样。 相关的是您正在使用的 EF 版本以及是否启用了任何延迟加载。

标签: c# entity-framework asp.net-core ef-code-first data-annotations


【解决方案1】:

这是因为在 EF Core 中默认不加载引用。 当你想要它们时,你必须强制包含。

_context.Listings.Include(m=>m.Organization)

您可以对要加载的任何其他字段重复此操作。

【讨论】:

  • 我已经在使用 Include 并且知道使用它的要点,但我想实现延迟加载,即当我从数据库中获取列表时,引用会自动填充。
  • 到目前为止我还不能正确地延迟加载。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-17
  • 1970-01-01
相关资源
最近更新 更多