Question

I have a new disconnected POCO (in my case from aspnet mvc modelbinder).

public class OfflineEntry
{
    public virtual int Id { get; set; }
    public virtual Category Category { get; set; }
    public virtual int CategoryId { get; set; }
}

The foreign key property (CategoryId) is set to an existing database value but the navigation reference (Category) is null at first. What is the right way to load the navigation reference? I expect step one is add the new object to the context. Then before SaveChanges, can I use lazy loading, or LoadProperty, or do I have to set it manually?

public ContentResult Save(OfflineEntry o)
{
    db.OfflineEntries.Add(o);
    var categoryName = o.Category.Name; //?
    db.SaveChanges();
    return Content("ok");
}

public class Category
{
    public virtual int Id { get; set; }
    public virtual string Name { get; set; }
    //optional 2-way nav property
}
Was it helpful?

Solution

I was hoping someone else would jump on this who is an expert, but one issue I see you're going to have is that your instance of OfflineEntry is not created from your DbContext, and thus LazyLoading isn't going to work.

Generally it is better practice to not use your entity models as your view models, this being one of the reasons.

So my suggestion would be to create an NewOfflineEntryViewModel like below:

public class NewOfflineEntryViewModel
{
    public int CategoryId { get; set; }
}

and then retrieve the Category from the DbContext manually

public ContentResult Save(NewOfflineEntryViewModel model)
{
    var category = db.Categories.Find(model.CategoryId);

    var newEntry = db.OfflineEntries.Create();
    db.OfflineEntries.Add(newEntry);
    newEntry.Category = category;

    db.SaveChanges();

    var categoryName = category.Name; //for whatever you needed with this

    return Content("ok");
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top