2
votes

I am creating a new project with ASP.NET Core & Entity Framework Core. (I think this is entity framework 7?)

I think MS have removed Lazy Loading, so my virtual collections are not loading automatically. So then I decided to try ".include" however this method was missing. So I included "System.Data.Entity" and now I have .include but it still loads the collections as null. The entites definitely have related data with in the database.

My Code is as follows:

//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; }
}

This is some of the things I tried in OnModelCreating with no success //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();

it should also be noted that I am using the built in IdentityDbContext as my Db Context. ie:

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
1
Does the following return null? _dbContext.Properties.Include(a => a.BodyCorpMembers) .FirstOrDefault(a => a.BodyCorpMembers.ToList().Count > 0)Drazen Bjelovuk

1 Answers

1
votes

I didn't figure out why it wasn't working, but I just upgraded EF Core to 1.1 and used explicit loading.

ie:

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

This works fine.

I do hope MS brings back Lazy loading however.

update After updating to Entity framework core 1.1 .include started working also.