gpt4 book ai didi

sql-server - 在 C# Visual Studio 数据库中查询特定表

转载 作者:搜寻专家 更新时间:2023-10-30 23:16:07 24 4
gpt4 key购买 nike

我是 Visual Studio MVC3 的新手,正在尝试连接到数据库。我在 web.config 文件中有我的连接字符串:

add name="con" connectionString="Data Source=190.190.200.100,1433;Network Library=DBMSSOCN;Initial Catalog=myDataBase; User ID=myUsername;Password=myPassword;" providerName="System.Data.SqlClient"

但是,服务器有多个表。在查询数据库时,我将如何/在何处指定要使用的表?

编辑:
例如,我正在查看 this example .应用程序如何区分表以显示数据?当您按照链接中的示例调用 return View(db.Students.ToList()) 时,应用程序如何知道要查看学生表而不是注册表?

最佳答案

How does the application differentiate between the tables to display data? When you call return View(db.Students.ToList()) as in the example in the link, how does the application know to look in the student table and not in the enrollment table?

db.Students部分来自 Entity Framework 。

阅读您发布的链接中的“创建数据库上下文”部分。
您会在那里找到以下代码:

using System;
using System.Collections.Generic;
using System.Data.Entity;
using ContosoUniversity.Models;
using System.Data.Entity.ModelConfiguration.Conventions;

namespace ContosoUniversity.Models
{
public class SchoolContext : DbContext
{
public DbSet<Student> Students { get; set; }
public DbSet<Enrollment> Enrollments { get; set; }
public DbSet<Course> Courses { get; set; }

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
}
}

这会设置数据库上下文,这基本上是 Entity Framework 的“设置”,从那里它知道必须将哪个 C# 类映射到数据库表。

所以 db.Students (根据你的问题)实际上是一个 DbSet<Student> .

Entity Framework 的默认约定如下所示:它尝试将类映射到具有相同名称的表。
通常,它会映射 Student。类到名为 Students 的表(复数),但您可以更改/覆盖这些约定......他们在此示例中也这样做了,在这一行中:

modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();

这个在教程里也有说明,直接在上面的代码下。
引自教程:

This code creates a DbSet property for each entity set. In Entity Framework terminology, an entity set typically corresponds to a database table, and an entity corresponds to a row in the table.

The statement in the OnModelCreating method prevents table names from being pluralized. If you didn't do this, the generated tables would be named Students, Courses, and Enrollments. Instead, the table names will be Student, Course, and Enrollment. Developers disagree about whether table names should be pluralized or not. This tutorial uses the singular form, but the important point is that you can select whichever form you prefer by including or omitting this line of code.

关于sql-server - 在 C# Visual Studio 数据库中查询特定表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13369391/

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