我们如何使用 linq 查询在 mvc 中从客户 table 中获取两列的名字和姓氏列表

How can we get list of two column say firstname and lastname from customer table in mvc using linq query

Customer Table

每次我 运行 我都会得到一个错误:

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]

代码:

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();
    }
}

您可以创建一个新的 Model class,它将包含您从 Customer class:

中选择的数据
public class GetCustomerInformation
{
 public string FirstName {get;set;}
 public string LastName {get;set;}
}

然后你可以 Select 像这样的要求:

IEnumerable<GetCustomerInformation>Name()   
{
    using (AdventureWorksLTDataContext db = new AdventureWorksLTDataContext())
    {
        return (IEnumerable<GetCustomerInformation>)db.Customers.Select(c => new GetCustomerInformation { FirstName = c.FirstName, LastName = c.LastName });
    }
}

我这里做了一个样例供大家参考。我手动将数据添加到列表,然后选择所需的内容:https://dotnetfiddle.net/CW9APV

现在,由于您正在查询数据库以获取数据,因此无法在查询过程中创建实体。实体可以在查询之外创建并使用 DataContext 插入到数据存储中。然后您可以使用查询检索它们。

所以解决方法是:

生成一个从您的 LINQ 派生的 class 到 SQL class:

internal class CustomerView: Customer { }

以这种方式编写您的查询:

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>())
    }
}