I have a problem with entity infrastructure in C #. I have 2 objects, User and UserRole. They are related by the relationship User * โ 1 UserRole
Whenever I use this request in a function:
User user = context.User.Where(i => i.id == id).FirstOrDefault(); return user.UserRole.accessLevel;
The request returns the user, but UserRole is null. The User table has a roleId, which is associated with the UserRole identifier, and the roleId value, if properly debugged, although the UserRole object is null. It's weird like never before ...
I have already made sure that my relationships in the model and database are correct. I have the correct rows added to the database.
EDIT:
Sorry, I should have mentioned that I am using a custom test database controller:
public class DBController : IUnitOfWork { readonly ObjectContext context; const string ConnectionStringName = "MarketPlaceDBEntities"; public DBController() { var connectionString = ConfigurationManager .ConnectionStrings[ConnectionStringName] .ConnectionString; context = new ObjectContext(connectionString); } public void Commit() { context.SaveChanges(); } public IObjectSet<Category> Category { get { return context.CreateObjectSet<Category>(); } } public IObjectSet<ItemComment> ItemComment { get { return context.CreateObjectSet<ItemComment>(); } } public IObjectSet<ItemRating> ItemRating { get { return context.CreateObjectSet<ItemRating>(); } } public IObjectSet<Item> Item { get { return context.CreateObjectSet<Item>(); } } public IObjectSet<ItemSale> ItemSale { get { return context.CreateObjectSet<ItemSale>(); } } public IObjectSet<ItemScreenshot> ItemScreenshot { get { return context.CreateObjectSet<ItemScreenshot>(); } } public IObjectSet<UserRole> UserRole { get { return context.CreateObjectSet<UserRole>(); } } public IObjectSet<User> User { get { return context.CreateObjectSet<User>(); } } }
And I perform operations through it. Maybe he should do something with my problem.
interface IUnitOfWork { IObjectSet<Category> Category { get; } IObjectSet<ItemComment> ItemComment { get; } IObjectSet<ItemRating> ItemRating { get; } IObjectSet<Item> Item { get; } IObjectSet<ItemSale> ItemSale { get; } IObjectSet<ItemScreenshot> ItemScreenshot { get; } IObjectSet<UserRole> UserRole { get; } IObjectSet<User> User { get; } void Commit(); }
I had it all before it worked, but I donโt know why it went wrong.
EDIT2:
Solved! Thanks RicoSuter.
Enabling lazy loading in the constructor of my db controller solved the problem. I thought it was already included because it was set to true in the database model, but it seems that when you create a new context, you must enable it again manually.
public DBController() { var connectionString = ConfigurationManager .ConnectionStrings[ConnectionStringName] .ConnectionString; context = new ObjectContext(connectionString); context.ContextOptions.LazyLoadingEnabled = true; }