【问题标题】:Loading Related Data with Entity Framework Core使用 Entity Framework Core 加载相关数据
【发布时间】:2016-12-23 01:59:05
【问题描述】:

我正在使用 ASP.NET Core 和 Entity Framework Core 创建一个新项目。 (我认为这是实体框架7?)

我认为 MS 已删除延迟加载,因此我的虚拟收藏不会自动加载。所以后来我决定尝试“.include”但是这个方法不见了。所以我包括了“System.Data.Entity”,现在我有了.include,但它仍然将集合加载为空。实体在数据库中肯定有相关数据。

我的代码如下:

//Property Table
public class Property
{
    public int Id { get; set; }

    public string PropertyName { get; set; }

    public string Address1 { get; set; }

    public string Address2 { get; set; }

    public string City { get; set; }

    public string Postcode { get; set; }

    public string State { get; set; }

    public string Country { get; set; }

    public string PhoneNumber { get; set; }

    public virtual ICollection<BodyCorpMember> BodyCorpMembers { get; set; }

    public bool Deleted { get; set; }
}

//Body Corp Table
public class BodyCorpMember
{
    public int Id { get; set; }

    public string FirstName { get; set; }

    public string LastName { get; set; }

    public string Email { get; set; }

    public bool IsSecretary { get; set; }

    public int Property_Id { get; set; }

    [ForeignKey("Property_Id")]
    public virtual Property Property { get; set; }
}

这是我在 OnModelCreating 中尝试过的一些事情,但没有成功 //builder.Entity() // .HasOne(a => a.Property) // .WithMany(a => a.BodyCorpMembers) // .HasForeignKey("Property_Id");

    //builder.Entity<Property>()
    //    .HasMany(a => a.BodyCorpMembers)
    //    .WithOne(a => a.Property);



    //Here is my main problem, Ive tried multiple options for ".include"   but it always returns null for BodyCorpMembers
          property = _dbContext.Properties.Include(a=>a.BodyCorpMembers).Where(a=>a.Id ==id).FirstOrDefault();

还应注意,我使用内置的 IdentityDbContext 作为我的 Db 上下文。即:

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>

【问题讨论】:

  • 以下是否返回null? _dbContext.Properties.Include(a =&gt; a.BodyCorpMembers) .FirstOrDefault(a =&gt; a.BodyCorpMembers.ToList().Count &gt; 0)

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


【解决方案1】:

我不知道为什么它不起作用,但我只是将 EF Core 升级到 1.1 并使用显式加载。

即:

property = _dbContext.Properties.Single(a=>a.Id == id);
_dbContext.Entry(property).Collection(a => a.BodyCorpMembers).Load();

这很好用。

我确实希望 MS 能够恢复延迟加载。

更新 更新到 Entity framework core 1.1 后,.include 也开始工作了。

【讨论】:

    猜你喜欢
    • 2020-06-16
    • 2017-08-01
    • 2021-12-03
    • 1970-01-01
    • 2023-04-02
    • 2019-02-23
    • 2021-06-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多