简体   繁体   中英

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.

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;
    }
}
var _Temp = entities.someTable.Select(x=> new{
                                               PropertyONE = x.PropertyONE,
                                               PropertyTWO = x.PropertyTWO 
                                             }).FirstOrDefault();
this.PropertyONE = _Temp.PropertyONE;
this.PropertyTWO = _Temp.PropertyTWO;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM