Tom
Tom

Reputation: 4087

Linq: how return property of specific object

i have the following model:

public partial class location
{
   public int Id { get; set; }
   public double Lat { get; set; }
   public double Long { get; set; }

   public virtual ICollection<localserver> localserver { get; set; }
}

When, in a controller, i do:

List<location> l = db.location.ToList();

i get also the localserver object. How, in LINQ, get only the property of location (Id, Lat and Long) without using the Select argument in linq?

Upvotes: 0

Views: 103

Answers (2)

anaximander
anaximander

Reputation: 7140

The way to extract part of an object is to project it to a new form, which is what .Select() is for:

var result = db.location
    .Select(x => new
    {
        Id = x.Id,
        Lat = x.Lat,
        Long = x.Long
    })
    .ToList();

Now, you've specifically asked how to do this without using .Select(), so... really, the answer is "you don't". You've ruled out the tool that's specifically designed for the scenario you're presenting, so no useful answer remains.

To address the intent of your question, however, I'm going to make a guess that you don't want to load the collection of localserver objects, perhaps because it's large and uses a lot of memory. To solve that problem, I would suggest the following:

  • If you're using Entity Framework Code First, check your cascade options when creating the database (if you're setting any).
  • Check that the collection is declared as virtual (you've shown it as such here but check the actual source)
  • Check that you have lazy-loading enabled, by setting myContext.ContextOptions.LazyLoadingEnabled = true; at some point

This should allow the application to lazy-load that property, which means that the contents of that localserver property will only be retrieved from the database and loaded into memory when they're actually needed. If you don't ever access it, it won't be loaded and won't take up any memory.

Upvotes: 3

Majed
Majed

Reputation: 53

When you are getting Location list entity is not pulling Localserver object data, the thing that entity framework has feature called lazy loading. Lazy loading means you can get associated object at any time you need, no need write one more separate linq query to get. This will pull data from associated object only when you call them inside the code, then entity framework will make one more call to database to load that associated object data.

So just go with your code, but if you want some selected columns from Location object itself than you have write Select and supply column names.

Upvotes: 0

Related Questions