Note that there are some explanatory texts on larger screens.

plurals
  1. POOne-to-Many Relationship in Entity Framework 4.1: foreign Id is retrieved, but the object itself not
    text
    copied!<p>I'm using Entity Framework 4.1 and trying to create a one-to-many relationship. In my software I have UserEntity and RoleEntity classes. Each User has one Role but one Role can have many Users.</p> <p>So far I've succeeded in getting the data from the DB to the UserEntity except for the related RoleEntity object. The RoleId property of my test user object has the correct RoleID but Role property is null.</p> <p>Is there some kind of additional configuration that I would need to write before the Role property is populated with the correct RoleEntity?</p> <pre><code>[Table("Roles")] public class RoleEntity { public long Id { get; set; } public string Name { get; set; } } [Table("Users")] public class UserEntity { public long Id { get; set; } public string Password { get; set; } public Int32 IsActive { get; set; } public string Username { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public string Email { get; set; } public string LocalService { get; set; } [ForeignKey("RoleEntity")] public long RoleId { get; set; } public virtual RoleEntity Role { get; set; } public virtual ClientOrganizationEntity ClientOrganization { get; set; } } public class UserContext : DbContext { #region Constructor public UserContext(DbConfigurationProvider dbConfigurationProvider) : base(dbConfigurationProvider.ConnectionString) { if (dbConfigurationProvider == null) throw new ArgumentNullException("dbConfigurationProvider"); Configuration.ProxyCreationEnabled = false; } #endregion #region DbSets public DbSet&lt;UserEntity&gt; Users { get; set; } public DbSet&lt;RoleEntity&gt; Roles { get; set; } public DbSet&lt;ClientOrganizationEntity&gt; ClientOrganizations { get; set; } #endregion } </code></pre> <p>Data in Users table:</p> <p>Id User Password FirstName LastName Email LocalService IsActive RoleId ClientOrganizationId</p> <p>1 foo 62cdb7020ff920e5aa642c3d4066950dd1f01f4d FirstName LastName te@s.t foobar.com 1 1 1</p> <p>Data in Roles table:</p> <p>Id Name</p> <p>1 Administrator</p> <p><strong>EDIT:</strong></p> <p>This how I get the data from the DbContext:</p> <pre><code>var user = _dbContext.Users.FirstOrDefault(x =&gt; x.Id == 1); var role = user.Role; </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload