Losbear
Losbear

Reputation: 3315

Load class properties using LINQ

I'm currently setting the properties in a class like this:

MyClass _Temp = (from x in entities.someTable 
    select new MyClass {
        PropertyONE = x.PropertyONE,
        PropertyTWO = x.PropertyTWO
    }).FirstOrDefault();

this.PropertyONE = _Temp.PropertyONE;
this.PropertyTWO = _Temp.PropertyTWO;

But i'm thinking there has to be a better way than creating another instance of the class as a placeholder just to end up populating the real one - something like this?

this = (from x in entities.someTable 
    select 
        PropertyONE = x.PropertyONE,
        PropertyTWO = x.PropertyTWO
    ).FirstOrDefault();

Any ideas?

* EDIT: MORE INFO ** How I'm using this:

In an MVC controller I have:

public ActionResult Index(Guid id)
{
    MyClass model = new MyClass(id);
    Return View(model);
}

And in the constructor of "MyClass" I have the code above that I want it to 'preload' the class (it's properties) with data to display on the view.

Hope this explains it better.

Upvotes: 0

Views: 242

Answers (2)

Cyril Gandon
Cyril Gandon

Reputation: 17048

Yes, it should be simpler:

var first = entities.someTable.FirstOrDefault();
if(first != null)
{
    this.PropertyONE = first.PropertyONE;
    this.PropertyTWO = first.PropertyTWO;
}

Edit : split you code in layer:

Data Access Layer

public static Entity GetById(int id)
{
    using(var entities = new MyEntities())
    {
        return entities.someTable
                       .FirstOrDefault(row => row.Id == id);
    }
}

Controller Layer

public ActionResult Index(Guid id)
{
    MyClass model;
    // call the DAL
    var entity = DataAccess.GetById(id);

    // call the model
    if(entity != null)
    {
        model = new MyClass(entity);
    }
    else
    {
        model = null;
    }
    Return View(model);
}

Model Layer

public class MyClass
{
    public MyClass(Entity entity)
    {
        this.PropertyONE = entity.PropertyONE;
        this.PropertyTWO = entity.PropertyTWO;
    }
}

Upvotes: 4

Roar
Roar

Reputation: 2167

var _Temp = entities.someTable.Select(x=> new{
                                               PropertyONE = x.PropertyONE,
                                               PropertyTWO = x.PropertyTWO 
                                             }).FirstOrDefault();
this.PropertyONE = _Temp.PropertyONE;
this.PropertyTWO = _Temp.PropertyTWO;

Upvotes: 2

Related Questions