简体   繁体   中英

Populate navigation properties automatically?

I've this -simplified- model class:

public class Transaction
{
    public string Id { get; set; }
    public virtual UserResource Resource { get; set; }
}

And an Mvc Web Api Controller:

// POST api/values
[HttpPost]
public void Post([FromBody]Transaction transaction)
{
}

And my request body is like this:

{"Id":"5520AEB9-DAD8-4C85-80A7-3257931B9790","ResourceId":"118547FC-0B3A-4816-820C-93BF2BA1BF14"}

In the post method, transaction.Resource is null. And I don't know how to get it to be populated using the Resource Id I passed...

What I tried so far:

  1. Add public string ResourceId {get; set;} public string ResourceId {get; set;} and mark it as a ForeignKey in Transaction... -> no change
  2. In the request change ResourceId param to "Resource":{Id:".."} -> transaction.Resource is not null any more but it hasn't queried Resource table to fill in anything...
  3. Mark Resource as virtual or not (Lazy loading or Eager) -> No change

Ideas?

You are not passing the Resource object to your API, you must either pass it in or have the API figure out what it is, I don't suggest the latter.

So as it's Entity Framework 7, you can't use lazy loading at this point in time as it's not (yet) in the framework.

The current roadmap lists it as a high priority and they state:

These features are high priority but we think EF7 would be a compelling release for the vast majority of applications without them.

So instead, in your query you need to manually include all of your navigation properties, for example:

var data = context.Transactions
    .Include(t => t.Resource)
    .Where(t => t.Id == 1);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM