-1

I have two tables: Post and User.

the User has an Id and Name... fields. and the Post has an userId and Title... fields.

im using linq, and i want to be able to write something like this:

var post = dc.Posts.FirstOrDefault();
var user = post.User;

then i want to be able to do: post.User.Name ...

help please..

HasanAboShally
  • 18,459
  • 7
  • 30
  • 34

1 Answers1

0

Assume you are using Entity Framework. Make sure that you have navigation properties on your entities, and that lazy loading is enabled. Your code should work then:

var post = dc.Posts.FirstOrDefault();
if (post != null)
    name = post.User.Name;

Also you can do eager loading of User entity when you are loading post:

var post = dc.Posts.Include(p => p.User).FirstOrDefault();
if (post != null)
    name = post.User.Name;    
Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459