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.
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.
Is there some kind of additional configuration that I would need to write before the Role property is populated with the correct RoleEntity?
[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<UserEntity> Users { get; set; }
public DbSet<RoleEntity> Roles { get; set; }
public DbSet<ClientOrganizationEntity> ClientOrganizations { get; set; }
#endregion
}
Data in Users table:
Id User Password FirstName LastName Email LocalService IsActive RoleId ClientOrganizationId
1 foo 62cdb7020ff920e5aa642c3d4066950dd1f01f4d FirstName LastName [email protected] foobar.com 1 1 1
Data in Roles table:
Id Name
1 Administrator
EDIT:
This how I get the data from the DbContext:
var user = _dbContext.Users.FirstOrDefault(x => x.Id == 1);
var role = user.Role;