【问题标题】:How to display in a console values from SQL Server using Entity Framework Core?如何使用 Entity Framework Core 在 SQL Server 的控制台中显示值?
【发布时间】:2020-12-29 20:26:54
【问题描述】:

我有一个简单的 SQL Server 数据库表 PersonsPersonID, Name, Age - 4 行)。我想在使用 Entity Framework Core 的控制台应用程序中显示此值。

我的班级:

class Person
{
    public int PersonID { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
}

class AppDbContext : DbContext
{
    private const string stringConnection = @"Server=localhost; Database=Persons; Trusted_Connection=True;";

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlServer(stringConnection);
    }

    public DbSet<Person> Persons { get; set; }
}

Persons

我应该编写什么代码来在控制台应用程序中显示这些值?

【问题讨论】:

  • 向我们展示您的迄今为止的努力!你被困在哪里了?我们会提供帮助 - 但不仅仅是为您编写整个代码......

标签: c# .net entity-framework-core console-application


【解决方案1】:

您应该将AppDbContext 传递到您的存储库、业务逻辑或控制器,或者您想要查询的位置

之后,您可以执行以下操作:

AppDbContext _context;
public YourClassName(AppDbContext context)
{
 _context = context;
}
public object YourMethod()
{
var result = _context.YourTable.ToList();
return result;
}

你会得到一个列表 T 是 entityframework 生成的实体类

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-05-31
    • 2018-09-02
    • 2019-08-16
    • 1970-01-01
    • 1970-01-01
    • 2017-10-19
    • 1970-01-01
    • 2016-06-30
    相关资源
    最近更新 更多