In my application I have many entities.
Two of them are Person and Company, which have a many-to-many relationship.
So in my code I have a Person class which contains a refeference to a collection of Companies (ICollection), and a Company class which contains a reference to a collection of people. (ICollection).
Using a first-code approach, the database was correctly generated. There are three tables: People, Companies and PeopleCompanies.
In the table PeopleCompanies I have a record which should create an association between determined Person and an other determined Company, as shown in the image below.
http://s27.postimg.org/xnkz3j94j/DBPrint.png
So, what is my problem?
In my business logic I need to know which people are associated to a determined Company, but the navigation property of the class Company remains empty: ICollection.Count() -----> 0
In realty, as you can see in the image above, there is exactly one person associated to the company.
I need the navigation property!
Someone can help?
The code of the DbContext is below. Thanks!
public class EnterpriseDataContext : DbContext
{
public EnterpriseDataContext(string connString) : base(connString)
{
}
#region CRM Module
public DbSet<Category> Categories { get; set; }
public DbSet<City> Cities { get; set; }
public DbSet<Company> Companies { get; set; }
public DbSet<CompanyNote> CompanyNotes { get; set; }
public DbSet<Country> Countries { get; set; }
public DbSet<Lead> Leads { get; set; }
public DbSet<Person> People { get; set; }
public DbSet<PersonNote> PersonNotes { get; set; }
public DbSet<Sector> Sectors { get; set; }
#endregion
}
My psychic debugging powers are telling me that lazy loading is enabled and you're not using the proper Includes.
First, you need to make sure you have the following using statement
using System.Data.Entity
And then use .Include()
to load your people.
var myEnterpriseDataContext = new EnterpriseDataContext("insert connection string here");
myEnterpriseDataContext.Companies
.Include(c => c.People)
//.Rest Of Query
note: you don't need includes for fields that you only access while executing your query. IE
myEnterpriseDataContext.Companies
.Select(c => new CompanyViewModel(){People = c.People});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.