CodeDemen
CodeDemen

Reputation: 1971

Entity framework child is null

I'm new to EntityFramework, so the question could be a bit stupid, but I've tried to searching google and found nothing.

I've got a table in db:

    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public Guid Id { get; set; }
    [Required]
    public UserProfile Owner { get; set; }
    [Required]
    public string Mask { get; set; }
    [Required]
    public string Key { get; set; }
    public DateTime Generated { get; set; }
    public DateTime DateTo { get; set; }
    public bool isElite { get; set; }

where UserProfile Owner is a link to another table. When I make a selection like so:

 db.Keys.Where(s=>s.Owner.UserId == WebSecurity.CurrentUserId && s.DateTo > DateTime.UtcNow).ToList()

It works well, but when I am trying to reach Owner from the licence it's always null. Can someone please help how to get the Owner with a license? Thank you for your time!

EDIT: I think I made a mistake and posted a question a bit incorrectly. What I truly need is when I am searching license by its ID like: License license = db.Keys.Find(id); I could get the owner like: var a = license.Owner; I've used Active Record before, and it loaded such data "on demand" (only when I make a call to it). Can I do this somehow with EF?

Upvotes: 2

Views: 4667

Answers (2)

Davin Tryon
Davin Tryon

Reputation: 67296

With the code you have, you can lazy load the Owner by marking it as virtual in the license class.

Since you are still in the context (using db), EF will automatically call to hydrate the Owner.

For a good article on loading related entities check this out.

EDIT (query with linq):

Here is an example of what the linq query might look like, but you still might need to either lazy or eager load Owners.

var query = from k in db.Keys
            where k.Owner.UserId.Equals(WebSecurity.CurrentUserId)
            && k.DateTo > DateTime.UtcNow
            select k;

var list = query.ToList();

Upvotes: 2

Gilles Radrizzi
Gilles Radrizzi

Reputation: 1009

Make use of the DbQuery.Include(string path) Method Click here

That at least does the trick for me.

Here would be your code:

db.Keys.Include("Owner").Where(s=>s.Owner.UserId == WebSecurity.CurrentUserId && s.DateTo > DateTime.UtcNow).ToList()

This might not be the best method if you expect your "Keys" query to return tons of results. But with only a limited number of results it is working like a charm.

Upvotes: 2

Related Questions