0

I'm trying to understand the difference in my one-to-many relationship after I add a virtual call back to my main entity 'space'. All it does, looking at the tables is create a constraint. Can someone please explain the difference between having

public virtual Space Space { get; set; }

and leaving it out?

Here is my main entity 'space' and 'spaceimage' that has the virtual call back to 'space'

public class Space
{
    public int SpaceId { get; set; }
    public virtual ICollection<SpaceImage> Images { get; set; }  
}

public class SpaceImage
{
    public int SpaceImageId { get; set; }
    public byte[] Image { get; set; }
    public byte[] ImageThumbnail { get; set; }
    public string ContentType { get; set; }
    public bool IsMain { get; set; }

    public virtual Space Space { get; set; } // adds a constraint in sql server
}

1 Answer 1

0

the difference is you can make a call like this :

  var thisSpace = _context.Space.Include( x => x.Images).Where( blah == blah);

ok, so know you got your space from the database , now you don't need any other query at all to get images, you would just do.

  thisSpace.Images // now this is filled with a collection of images 

You do not need a join , you don't need to do anything at all - see how awesome Entity Framework is. The down side... is the is some overhead in a framework that can do stuff like this.

UPDATE:

you asked about Lazy Loading , you still have control of lazy loading or not.

See if you were to do :

   var thisSpace = _context.Space.Include( x => x.Images).Where( blah == blah).ToList();

then the query will execute right away and the Images will be attached. or..

you could do something like

   var thisSpace = _context.Space.Include( x => x.Images).Where( blah == blah);
   foreach( var image in thisSpace.Images){
   // when you hit this in code the query will actually execute
   // if lazy loading
   }
4
  • hi Scott. If I have other entities inside my 'space' entity, ex. address, would I also be able to pull the address out in the same query? In your example you have just x => x.Images, but what if I wanted addresses, receipts, etc?
    – chuckd
    Mar 14, 2015 at 3:20
  • one more question. this would still be lazy loading the images right?
    – chuckd
    Mar 14, 2015 at 3:22
  • is that a no to lazy loading or a no to not being able to put more then images in the query?
    – chuckd
    Mar 14, 2015 at 3:31
  • I meant you still control Lazy loading - having relationships defined in the data objects has nothing to do with weather you are implementing lazy loading Mar 14, 2015 at 3:32

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.