gpt4 book ai didi

c# - 使用 Entity Framework 获得结果

转载 作者:太空宇宙 更新时间:2023-11-03 19:57:42 24 4
gpt4 key购买 nike

我正在尝试查询数据库集,但在获得结果时似乎无法访问数据。这是我试过的代码。

查询#1:

public List<CustomerMain> testing()
{
var context = new CustomerEntities();

var query = context.CustomerMains
.Where(p=> p.FirstName == "Thor")
.Select(p => new CustomerMain {FirstName=p.FirstName,LastName =p.LastName}).ToList();

return query;
}

查询#2:

public IQueryable<CustomerMain> testing()
{
var context = new CustomerEntities();

var query = context.CustomerMains
.Where(p=> p.FirstName == "Thor")
.Select(p => new CustomerMain {FirstName=p.FirstName,LastName =p.LastName});

return query;
}

CustomerMain 是我的 DbSet,如果我运行其中任何一个并将该方法分配给 var 变量,它不会给我任何选择来获取 FirstNameLastName 来自变量。我发现如果我将它转换为 CustomerMain 就可以做到,但是返回查询不应该已经是 CustomerMain 类型了吗?

最佳答案

it gives me no options to grab the FirstName or LastName from the variable

因为该方法返回的是一个集合或可查询对象,而不是单个实体。您需要迭代或选择记录:

var customers = testing();
foreach (CustomerMain customer in customers)
{
// access customer.FirstName
}

或者:

var customers = testing();
var oneCustomer = customers.FirstOrDefault(c => c.FirstName == "Thor");
// access oneCustomer.FirstName

或者,如果您希望该方法返回一条记录(如果未找到则返回 null):

public CustomerMain FindOne(string firstName)
{
using (var context = new CustomerEntities())
{
var query = context.CustomerMains.Where(p => p.FirstName == firstName);

return query.FirstOrDefault();
}
}

关于c# - 使用 Entity Framework 获得结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31655761/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com