Reputation: 2352
I'm a newbie in ASP.NET MVC4. This is my problem:
I have two tables as follow:
`Users(Username, Password, Email, RoleId)`
and
`Roles(Id, Name)`
Which Users.RoleId
is foreign key references to Roles.Id
This is my classes:
[Table("Users")]
public class User
{
[Key, Required, DatabaseGenerated(DatabaseGeneratedOption.None)]
[StringLength(20)]
public string Username { get; set; }
[StringLength(32), Required]
public string Password { get; set; }
[StringLength(70), Required]
public string Email { get; set; }
public int RoleId { get; set; }
public virtual Role Role { get; set; }
}
[Table("Roles")]
public class Role
{
public Role()
{
Users = new HashSet<User>();
}
[Key, DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public int Id { get; set; }
[StringLength(30)]
public string Name { get; set; }
public virtual ICollection<User> Users { get; set; }
}
public class Database : DbContext
{
public Database()
: base("WebstoreDbConnectionString")
{
}
public DbSet<User> Users { get; set; }
public DbSet<Role> Roles { get; set; }
}
Now, I can select all users in my DB with:
using (var db = new Database())
{
ViewBag.Users = db.Users.ToList();
}
and show it in view:
@foreach(var user in ViewBag.Users) {
<p>@user.Username | @user.Password</p>
}
but statement: @user.Role.Name
give me an error:
The ObjectContext instance has been disposed and can no longer be used for operations that require a connection.
What's cause the problem and how to solve this?
Upvotes: 2
Views: 84
Reputation: 18181
The above suggestion is good. However, the error message means that you have closed the connection when you try to access the Role Property from the user. It should work because you declared it as "virtual", which means that you want the lazy loading.
using (var db = new Database())
{
ViewBag.Users = db.Users.ToList();
}
When you try to use "using" to wrap the db connection, you have disposed the connection after the statement. If you could close the connection later, you shouldn't need the Include here.
Upvotes: 1
Reputation: 2378
try like this :
using (var db = new Database())
{
ViewBag.Users = db.Users.Include("Role").ToList();
}
Upvotes: 1