Every time I run this I get an error:
Unable to cast object of type 'System.Collections.Generic.List1[<>f__AnonymousType1 2[System.String,System.String]]' to type 'System.Collections.Generic.IEnumerable1[CRUD__MVC.Models.Customer]
Code:
public ActionResult FirstLastName()
{
return View(Name());
}
IEnumerable<Customer>Name()
{
using (AdventureWorksLTDataContext db = new AdventureWorksLTDataContext())
{
return (IEnumerable<Customer>)db.Customers.Select(c => new { FirstName = c.FirstName, LastName = c.LastName }).ToList();
}
}
You can create a new Model
class which will consist of your selected data from the Customer
class:
public class GetCustomerInformation
{
public string FirstName {get;set;}
public string LastName {get;set;}
}
And you can then Select
the required like this:
IEnumerable<GetCustomerInformation>Name()
{
using (AdventureWorksLTDataContext db = new AdventureWorksLTDataContext())
{
return (IEnumerable<GetCustomerInformation>)db.Customers.Select(c => new GetCustomerInformation { FirstName = c.FirstName, LastName = c.LastName });
}
}
I have made a sample here for you reference. I am manually adding data to the list and then selecting what is required: https://dotnetfiddle.net/CW9APV
Now since you are querying the DB to get your data, you can't create entities as part of a query. Entities can be created outside of queries and inserted into the data store using a DataContext
. You can then retrieve them using queries.
So a workaround would be:
Generate a class that derives from your LINQ to SQL class:
internal class CustomerView: Customer { }
Write your query in this way:
IEnumerable<Customer> Name()
{
using (AdventureWorksLTDataContext db = new AdventureWorksLTDataContext())
{
var query= db.Customers.Select(c => new CustomerView { FirstName = c.FirstName, LastName = c.LastName }).ToList();
//Cast it back to Customer
return (query.Cast<Customer>())
}
}
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.