2

Given the following SQL tables:

EntityGroup:
Id int, (PK)
GroupName nvarchar(100)

Entity:
Id int, (PK)
EntityGroupId int, (FK Non-nullable)
Description nvarchar(100)

And the following POCOs

  public class Entity
  {
    public int Id { get; set; }
    public int EntityGroupId { get; set; }    
    public int RefNumber { get; set; }
  }    

  public class EntityGroup
  {
    public int Id { get; set; }    
    public virtual IList<Entity> Entities { get; set; }
  }

How do I configure the fluent mapping correctly? I want Entity.EntityGroupId to remain as an int rather than an EntityGroup object.

I want to be able to .Include() optionally Include("Entities"). The closest I got is this, but that seems to eager-load all entities even if I dont use .Include("Entities"), which is not the behaviour I want:

modelBuilder.Entity<EntityGroup>()
        .HasMany(x => x.Entities);
Marcus K
  • 779
  • 1
  • 10
  • 22
  • [Lazy Loading?](http://stackoverflow.com/questions/2866881/why-does-the-entity-framework-need-an-icollection-for-lazy-loading) – Jivan Feb 28 '17 at 18:44

3 Answers3

3

You must set off the lazy loading, you can do this for just a specific unit of work or for all by setting your dbContext Like

   dbContext.Configuration.LazyLoadingEnabled = false;
   dbContext.Configuration.ProxyCreationEnabled = false;

or set it in Ctor of your DbContext.

S.Cheginy
  • 424
  • 2
  • 15
2

The way I understand it, you want to configure one-to-many relationship between EntityGroup and Entity without navigation property in Entity class and using Entity.EntityGroupId as a FK. All that with Fluent API.

It's possible, but you have to start the configuration from the class having a navigation property (EntityGroup in your case) because Has methods require property accessor while With methods have parameterless overloads. As usual, for the last part you will use the HasForeignKey method:

modelBuilder.Entity<EntityGroup>()
    .HasMany(e => e.Entities)
    .WithRequired()
    .HasForeignKey(e => e.EntityGroupId);

But note that EF recognizes the naming convention used in your sample classes (in particular the EntityGroupId), so you'll get the same mapping w/o any fluent configuration or data annotations.

Ivan Stoev
  • 195,425
  • 15
  • 312
  • 343
1

The problem is lazy loading is enabled by default, so it will load the related entities every time you try to get access to them.Two options to solve your issue could be:

  1. Disabling lazy loading in your context:

    public YourContext()
    {
        this.Configuration.LazyLoadingEnabled = false;
    }
    
  2. Removing virtual from your navigation property, which is one of the requirements to work lazy loading and the tracking change:

    public ICollection<Entity> Entities { get; set; }
    

If you want to learn more about the supported ways you can load related entities in EF I suggest you to read this article

ocuenca
  • 38,548
  • 11
  • 89
  • 102