简体   繁体   中英

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

I am using Database first approach in Entity framework. I have two tables ie 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?

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.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM