【问题标题】:Navigation properties not loaded properly [duplicate]导航属性未正确加载[重复]
【发布时间】:2020-12-16 03:33:31
【问题描述】:

我有以下课程:

public class Home
{
    [Key]
    public string Name { get; set; }

    [ForeignKey("Header")]
    public int HeaderID { get; set; }

    public Content Header { get; set; }
}

public class Header 
{
    //...sone attributes

    public ICollection<Home> Homes { get; set; }
}

在将 Header 设为 null 之前,我无法获取数据

Home item= BookingContext.Home.Include("Slides").FirstOrDefault();
item.Header = null;

有没有更好的方法,因为我认为我的方法不正确。

【问题讨论】:

  • 问题不清楚。 I can't get data till making the Header null 是什么意思?显然,您正在加载一个item,否则您会得到一个 NullReferenceException
  • @PanagiotisKanavos 问题是当我从数据库中获取数据时,导航属性就像在检索数据时循环一样,因为标题有主页列表。
  • @NoahLc 这与您所写的相反,但仍不清楚并且可能不是发生了什么。您首先编写的内容意味着没有加载任何数据。您现在写的内容是关于无限循环,但没有显示任何循环。真正的问题是什么?
  • 您是否收到 JSON.NET 错误,抱怨自引用循环?这与实体框架无关。为避免这种情况,tell Json.Net to ignore the loop
  • @PanagiotisKanavos 对不起,我的解释不好,您的回答就是解决方案,谢谢。你可以把它作为接受它的答案。

标签: c# asp.net entity-framework


【解决方案1】:

使用.Load()方法:

using (var context = new BloggingContext())
{
    var post = context.Posts.Find(2);

    // Load the blog related to a given post.
    context.Entry(post).Reference(p => p.Blog).Load();

    // Load the blog related to a given post using a string.
    context.Entry(post).Reference("Blog").Load();

    var blog = context.Blogs.Find(1);

    // Load the posts related to a given blog.
    context.Entry(blog).Collection(p => p.Posts).Load();

    // Load the posts related to a given blog
    // using a string to specify the relationship.
    context.Entry(blog).Collection("Posts").Load();
}

更多关于显式加载https://docs.microsoft.com/en-us/ef/ef6/querying/related-data

【讨论】:

  • 如果Include 存在问题,则没有理由认为Load 应该可以工作。
猜你喜欢
  • 2014-07-21
  • 2016-11-21
  • 2016-12-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多