0

Edit: from googling I just found out EF7 does not support lazy loading, so how would I accomplish this?

I have the following:

[Table("MediaSubmission")]
public class MediaSubmission
{
    [Key]
    public int Id { get; set; }

    public string Title { get; set; }

    public virtual MediaItem Item { get; set; }
}

[Table("MediaItem")]
public class MediaItem
{
    public int Id { get; set; }

    [Required]
    [DataType(DataType.Url)]
    public string MediaContents { get; set; }
}

I create a MediaSubmission and a MediaItem to add to the database as follows:

var item = new MediaItem() { MediaContents = mediaSubmission.URL };
_context.Add(item);

var submission = new MediaSubmission() { Item = item, Title = mediaSubmission.Title };
_context.Add(submission);

await _context.SaveChangesAsync();

return true;

Inspecting the database, there's an ItemId in the MediaItem table which points to the primary key ID in mediaSubmission.

However when I iterate over the MediaSubmissions, I get a null reference exception for the Item.

I haven't overridden OnModelCreating.

Any ideas what's going on?

Edit: just to add this is the ApplicationbContext:

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
    {
    }

    public DbSet<MediaSubmission> ItemSubmissions { get; set; }
    public DbSet<MediaItem> Items { get; set; }

    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);
    }
}

I added ItemSubmissions and Items to it.

1

1 Answer 1

-1

how are you retrieving the MediaSubmissions when you say "iterate over the MediaSubmissions"?

You may need to retrieve the Item data for those objects like this:

_context.MediaSubmissions.Include("Item").ToList();

EDIT:

To allow lazy loading, try putting this.Configuration.LazyLoadingEnabled = true; inside the constructor of your class that enherits DbContext.

See here for info about lazy loading: http://www.entityframeworktutorial.net/EntityFramework4.3/lazy-loading-with-dbcontext.aspx

1
  • I'm just looking through it from the dbcontext. I thought it would lazily create the media item when I access it otherwise it would be very slow to create all the foreign key relationships before being requested..
    – meds
    Aug 19, 2017 at 4:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.