Get entity navigation properties after insert

前端 未结 6 805
花落未央
花落未央 2020-12-23 02:14

I have the following 2 classes:

public class Reward 
{
    public int Id { get; set; }
    public int CampaignId { get; set;
    public virtual Campaign Camp         


        
6条回答
  •  攒了一身酷
    2020-12-23 03:10

    I have a simple Solution around the problem.

    instead of adding the CampaignID to the reward, add the campaign Object.. so:

    var _campaign = context.Campaign.First(c=>c.Id == 1);//how ever you get the '1'
    var reward = new Reward { Campaign = _campaign };
    context.Set().Add(reward);
    context.SaveChanges();
    
    //reward.Campaign is not null
    

    Entity framework does all the heavy lifting here.

    You're probably thinking that it's a waste to load the entire Campaign object but if you are going to be using it (from what it looks like, seems you are) then I don't see why not. You can even use the include statement when fetching it above if you need to access navigation properties from the Campaign object...

    var _campaign = context.Campaign.include(/*what ever you may require*/).First(c=>c.Id = 1);
    

提交回复
热议问题