Pete
Pete

Reputation: 3

Convert database entity to list in Visual Studio

I have a Visual Studio project where I have imported my table using database entity.

My database connection is named MyDBEntities and my table name is Full.

So my view of my table Full is:

private MyDBEntities db = new MyDBEntities();

public ActionResult Index()
{
   return view(db.Full)
}

This works fine.

My model name is FULL and has these properties:

Int id, string Firstname, string Lastname

I need to put my database data into a list instead, how can I convert this?

List<Full> myList = ......

Upvotes: 0

Views: 641

Answers (2)

Wael Mourad
Wael Mourad

Reputation: 164

Use Linq convert entities to list

public ActionResult Index()
{
    return view(db.Full.ToList())
}

Upvotes: 0

Paul Abbott
Paul Abbott

Reputation: 7211

var items = db.Full.Select(f => new Models.Full()
{
    Id = f.Id,
    FirstName = f.FirstName,
    LastName = f.LastName
});

return View(items);

Will cast the Full entities as Full models; items is going to be IEnumerable<Models.Full>. You don't really want a list because that will load everything into memory instead of enumerating one row at a time.

Upvotes: 2

Related Questions