Reputation: 37
Roles and Privileges have relationship 1 to many. but while retrieving roles i am getting null value "[]" for the privileges. I am using Json to send data to wcf services using EF6 having code first approach.
code :
System.Web.Script.Serialization.JavaScriptSerializer objJSSerializer =
new System.Web.Script.Serialization.JavaScriptSerializer();
string strJSON1 = objJSSerializer.Serialize((
from role in context.Roles select role)
.ToList());
output:
[{"privileges":[],"users":[],"ID":1,"RoleName":"Admin","IsActive":1},
{"privileges":[],"users":[],"ID":2,"RoleName":"Apprisal Minister","IsActive":0}]
I tried context.Configuration.ProxyCreationEnabled = false;
but still not able to get the privileges.
Basically, The problem, I am getting is that when i try to serialize the roles object. It doesn't serialize the relational data. I mean privileges are not there.
Which is the right way to get relational data in entity framework6.
Upvotes: 0
Views: 103
Reputation: 15294
Entity framework has lazy loading enabled by default which means that related items are not automatically retrieved from the database.
Let's imagine you have a blog containing multiple blog posts, each blog post has an author and many comments
1 Post has 1 Author
1 Post has many Comments
1 Comment has 1 Author
1 Author has many posts
1 Author has many comments
Now to retrieve a blog posts with the related author of the post, the comments and the authors of the comments, you need to use the Include()
extension method on your DbSet<TEntity>
with the name of the related type added as a parameter..
using(var context = new BlogContext)
{
var blogsDetailed = context.Blogs.Include("Author")
.Include("Comments.Author);
}
There may be syntax errors as I'm typing from iPhone but that's the idea behind it
Upvotes: 0
Reputation: 1904
Not sure if you mean load the Roles and it's related Privileges but this should work
var roles = dbContext().Roles.Include(r => r.Privileges);
And to serialize it use Newtonsoft.Json ( nugget package ) it handels relations but not circular refs. so if any references in Privileges to Roles , use attribute [JsonIgnore]
on the properties
string json = JsonConvert.SerializeObject(roles);
Upvotes: 1