J. Edmond
J. Edmond

Reputation: 41

Loading specific properties from the object in EF C# query

Please see the following query:

Blogs = await _context.Blog
            .Include(b => b.Owner)
            .ToListAsync();

this query will load all the blogs and the Owner (User object) of each blog, how i can load specific fields from the Owener object ?

for example i want only to load Owner.Name and Owener.ID , i don't need to the other info (Email, Phone, Password, ....)

Upvotes: 1

Views: 141

Answers (3)

Stefan
Stefan

Reputation: 17658

Do it manually;

var someData = await (
        from blog in _context.Blog
        join owner in _context.Users on blog.OwnerID equals owner.ID
        select new { Text = blog.Text, OwnerName = owner.Name}) //select whatever you want
        .ToListAsync();

This ensures only the data requested is "loaded" from the database.


Another option is to select from your query, if you are using lazy loading, this will not ensure the data isn't queried from the database:

var someData = await _context.Blog
        .Include(b => b.Owner)
        .Select(c => new { Text = c.Text, OwnerName = c.Owner.Name}) //select what needed
        .ToListAsync();


Since your case directly selects the data, the include is not necessary:

var someData = await _context.Blog
        .Select(c => new { Text = c.Text, OwnerName = c.Owner.Name}) //select what needed
        .ToListAsync();

Upvotes: 2

Llazar
Llazar

Reputation: 3312

You can use this code:

Blogs = await _context.Blog
            .Include(b => b.Owner)
            .Select(b => new
            {
              Name = b.Name,
              Id = b.OwnerID
            })
            .ToListAsync();

Upvotes: 0

Phan Dinh
Phan Dinh

Reputation: 285

You can use Select like this:

Blogs = await _context.Blog
            .Include(b => b.Owner)
            .Select(x => new {x.Owner.ID, x.Owner.Name})
            .ToListAsync();

Upvotes: 0

Related Questions