创建记录后,相关实体的引用消失了

时间:2019-07-17 08:22:36

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

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

如下面的图片所示,引用是使用组织实体创建的。

enter image description here

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

enter image description here

组织实体

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。

1 个答案:

答案 0 :(得分:1)

这是因为默认情况下,不会在EF Core中加载引用。 当您需要它们时,您必须强制包括。

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

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

相关问题