I have made the below properties as true.
Configuration.LazyLoadingEnabled = true;
Configuration.ProxyCreationEnabled = true;
I have two classes :
public partial class User : BaseEntity
{
public User()
{
this.UserRoles = new List<UserRole>();
}
public int UserId { get; set; }
public string FirstName { get; set; }
public virtual ICollection<UserRole> UserRoles { get; set; }
}
public partial class UserRole : BaseEntity
{
public int UserRoleId { get; set; }
public int UserId { get; set; }
public int RoleId { get; set; }
public virtual User User { get; set; }
}
I am calling a stored procedure from EF 6 like this :
public IEnumerable<User> GetUserDetails(int? userId)
{
var userIDParameter = userId.HasValue ?
new SqlParameter("@UserId", userId) :
new SqlParameter("@UserId", typeof(int));
return _dbContext.Database
.SqlQuery<User>("usp_GetUserDetails @UserId", userIDParameter);
}
Calling in Controller like this :
IEnumerable<User> user = _storedProcedureService.GetUserDetails(5);
In my SP I have logic as :
Select * from User where UserId = @UserId
I get all the data related to User but UserRoles.Count comes as zero.
What I am doing wrong ?
You are asking about using Lazy Loading with Entity Framework while you are using ADO.NET. ADO.NET does not support Lazy Loading, Entity Framework does.
For your info, this is ADO.NET;
var userIDParameter = userId.HasValue ?
new SqlParameter("@UserId", userId) :
new SqlParameter("@UserId", typeof(int));
return _dbContext.Database.SqlQuery<User>("usp_GetUserDetails @UserId", userIDParameter);
Which uses SqlParameter and stuff like that.
This is Entity Framework;
using (var db = new MyContext())
{
return db.User.Single(u => u.UserId = id);
}
Or, with stored procedures;
using (var db = new MyContext())
{
return db.GetUserDetails(id);
}
If you want to let Entity Framework handle stored procedures and support Lazy Loading, I suggest you follow this tutorial.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With