Using Database first approach in Entity framework, how to fetch the data from a single table only which has multiple foreign key relationship?

asp.net asp.net-mvc-4 c# entity-framework-6

Question

I am using Database first approach in Entity framework. I have two tables i.e. Person and Role table. Person table has 3 columns

  • PersonId
  • Name
  • RoleId

Role table has 2 columns

  • RoleId
  • RoleName

The automated generated classes for these two tables are below along with the foreign key relationship.

public partial class Role
{
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
    public Role()
    {
        this.People = new HashSet<Person>();
    }

    public int RoleId { get; set; }
    public string RoleName { get; set; }

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<Person> People { get; set; }
}

public partial class Person
{
    public int PersonId { get; set; }
    public string Name { get; set; }

    public virtual Role Role { get; set; }
}

I used following code to retrieve the data from Role table

    public List<Role> GetRole()
    {
        var _context= new TestDBEntities();
        List<Role> data = new List<Role>();
        data  = _context.Roles.ToList();
        return data;
    }

While retrieving the data from the Role table, all the data from the Role table was retrieved but the Person table data was also retrieved along with it. The reason behind it must be the relationship between these two tables. So, I want to fetch the data only from the Role table. Can anyone assist me on how to fetch the data from the Role table only without the data from Person?

1
0
7/17/2016 11:11:41 AM

Accepted Answer

The related data is not retrieved by the shown code, but when some other code does access People property for the first time. It could be the debugger variables window or some serialization code.

This behavior is called Lazy Loading. It can be disabled in a several ways, the easiest is to remove the virtual keyword from the navigation properties. In Code First you would do that directly in the code, in the EDMX designer I guess there must be some property controlling the generated property accessor. Or using the techniques described in the Selective disabling of lazy loading with Database First method thread.

3
5/23/2017 12:32:39 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow