【问题标题】:Using Entity Framework to return a very specific set of data from MSSQL使用实体框架从 MSSQL 返回一组非常具体的数据
【发布时间】:2019-04-11 00:42:02
【问题描述】:

按照 Microsoft 教程,我能够使用 Enitity Framework 创建一个 .NetCore 2.1 网站。

Web 应用程序连接到 MS SQL 数据库并使用脚手架将数据库表转换为类。

但它在幕后所做的只是基本查询,例如“select * from myTable”等。

例如,我有一个简单的控制器,它只获取 PlayerList 表中的所有玩家:

        // GET: PlayerLists
    public async Task<IActionResult> Index()
    {
        return View(await _context.PlayerList.ToListAsync());
    }

这个有点复杂,但实际上只是获取一个 Player:

        // GET: PlayerLists/Edit/5
    public async Task<IActionResult> Edit(int? id)
    {
        if (id == null)
        {
            return NotFound();
        }

        var playerList = await _context.PlayerList.FindAsync(id);
        if (playerList == null)
        {
            return NotFound();
        }
        return View(playerList);
    }

这可行,但我需要更复杂的东西才能从我的数据库中获取一组非常具体的数据。

如何使用 SQL 连接、case 语句和 group by 子句添加运行非常具体的查询的查询?

谢谢!

【问题讨论】:

标签: entity-framework asp.net-core asp.net-core-mvc


【解决方案1】:

在 EF Core 2.1 中,我们使用 Linq 来查询数据。您可以看到如何使用 Joins here 和 group by here。 Transact sql CASE WHEN THEN 的 linq 等价物是条件运算符?:

下面是一个简单的演示,结合它们进行查询:

1.模型

public class Product
{
    [Key]
    public int ProductID { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }

    public int CategoryID { get; set; } 
    public Category Category { get; set; }
}
public class Category
{
    [Key]
    public int CategoryID { get; set; }
    public string Name { get; set; }


    public IList<Product> Products { get; set; }
}

2.在控制器中查询

var result = from p in _context.Products
                     group p by p.CategoryID into pg
                     // join *after* group
                     join c in _context.Categories on pg.FirstOrDefault().CategoryID equals c.CategoryID
                     select new
                     {
                         CategoryName = c.Name == "oldName" ? "newName" : c.Name,//Replace Case statement
                         Products = pg
                     };

【讨论】:

    猜你喜欢
    • 2014-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-26
    • 2018-01-16
    • 1970-01-01
    相关资源
    最近更新 更多