C# 创建记录后,相关实体的引用消失
我正在用实体框架编写一个简单的.net核心应用程序。我有一种情况,保存记录后相关实体的引用为空。请参阅下面的代码和屏幕截图以了解更多信息 正如您在下图中看到的,引用是使用组织实体创建的 但是当我从上下文中获得所有列表时,引用就消失了 组织实体C# 创建记录后,相关实体的引用消失,c#,entity-framework,asp.net-core,ef-code-first,data-annotations,C#,Entity Framework,Asp.net Core,Ef Code First,Data Annotations,我正在用实体框架编写一个简单的.net核心应用程序。我有一种情况,保存记录后相关实体的引用为空。请参阅下面的代码和屏幕截图以了解更多信息 正如您在下图中看到的,引用是使用组织实体创建的 但是当我从上下文中获得所有列表时,引用就消失了 组织实体 public class Organization { public Organization() { this.Listings = new List<Listing>(); this.Co
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;
}
}
public IEnumerable GetAll()
{
返回_context.Listings;
}
公开列表GetById(int-id)
{
return\u context.Listings.Find(id);
}
公开挂牌创建(挂牌)
{
尝试
{
var org=_context.Organizations.SingleOrDefault(x=>x.Id==listing.OrgId);
org.Listings.Add(listing);
_context.Listings.Add(listing);
_SaveChanges();
返回列表;
}
捕获(例外情况除外)
{
掷骰子;
}
}
目前,我在Linq中使用Include来获取相关实体,但我需要所有相关实体而不使用Include。这是因为默认情况下,EF Core中不会加载引用。 当你想要它们时,你必须强制包含它们
_context.Listings.Include(m=>m.Organization)
您可以对要加载的任何其他字段重复此操作。我对这些图像感到困惑。你能不能以一种可读的方式提供你用过的代码,让我看看?另外,您说过您正在使用Include来获取相关实体,但是您需要在不使用Include的情况下获取所有相关实体-这就是Include的全部要点,除非您编写单独的查询来从每个DbSetI获取每个实体,否则您无法不使用Include。我更新了代码部分,希望现在有一些意义。因为我使用的是Include,但我只需要知道一个问题,即当我得到列表时,为什么它会变为null。这个问题可以归结为一个方法:
GetAll()
+类。其余部分(包括屏幕转储)与此无关。您从数据库中获取列表,但它们没有填充引用。这就是全部。与此相关的是您正在使用的EF版本,以及是否启用了任何延迟加载。我已经使用了Include,并且知道使用它的意义,但我希望实现延迟加载,即当我从数据库中获取列表时,会自动填充引用。到目前为止,我还无法正确地获得延迟加载。