1

I have these models :

public class Project
{
    public int ProjectID { get; set; }
    public string ProjectTitle { get; set; }
    public string ProjectDetails { get; set; }
    public Bid SelectedBid { get; set; }

    public virtual ICollection<Bid> Bids{ get; set; }

}
public class Bid
{
    public int BidID { get; set; }
    public string BidTitle { get; set; }
    public string BidDetails { get; set; }

    public virtual Project Project { get; set; }
}

And I have this Razor :

@if(Model.SelectedBid == null)
{
   <dt>
      Status : 
   </dt>

   <dd>        
      Bid not Selected
   </dd>
}
else
{
   <dt>
      Status : 
   </dt>

   <dd>
      Bid Selected.
   </dd>    
}

While debugging in the View, Model has this selected bid :

base = {System.Data.Entity.DynamicProxies.Bid_88FA74D99E4E553A1039D70D55E452C7931E74DCCCA8B5237C0A208B12CCA8C4} But it still accepts null situation.

Here is my controller :

 public ActionResult Details(int? id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        Project project = db.Projects.Find(id);
        return View(project);
    }

Can you tell me what is wrong with this code? Thanks.

7
  • you should debug the view, and check if SelectedBid is null or not Commented Dec 17, 2015 at 13:12
  • 6
    What does your controller look like? Commented Dec 17, 2015 at 13:13
  • @FabioLuz I checked in the View, it's still not null. But it says bid not selected. Commented Dec 17, 2015 at 13:16
  • @jason did you mean the SelectedBid is not null and the comparison SelectedBid == null is returning true? Commented Dec 17, 2015 at 13:20
  • @FabioLuz yes, I edited the question. Commented Dec 17, 2015 at 13:23

1 Answer 1

3

Try this in your action method:

Project project = db.Projects
    .Include(p=>p.SelectedBid)
    .FirstOrDefault(p=>p.ProjectID==Id);

Also don't forget to add System.Data.Entity namespace.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, worked like a charm. Can you tell the magic of Include?
EF doesn't fetch relative objects which associated with requested object from DB. Instead make a proxy object to lazy load the object. Therefore when you check Model.SelectedBid == null it returns true because it is not loaded yet and obviously null. But if you debug the code you can see actual data not a null object because debugger loaded the object while you debug the code. By adding include we say to EF fetch included object also and doesn't lazy load it.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.