简体   繁体   English

如何编写处理与用C#中的外键连接的表的Web API?

[英]How do I write a Web api which deals with tables that are connected with a foreign key in c#?

I am trying to write a web api for a student table and the lessons that the student takes. 我正在尝试为学生表和学生参加的课程编写一个Web API。 The controllers are working fine individually. 控制器单独运行正常。 I mean get, post, put and delete methods are working. 我的意思是获取,发布,放置和删除方法都有效。

Student Table has an id as primary key, a name and courses 学生表具有一个ID作为主键,一个名称和课程

Courses Table has an id as primary key, student id as foreign key and the name of the course 课程表具有一个ID作为主键,学生ID作为外键以及课程名称

The model classes are 模型类是

    public class Student
    {
        public int id { get; set; }
        public string name{ get; set; }
        public ICollection<Courses> Courses { get; set; } 
    }

    public class Courses
    {
        public int id { get; set; }
        public int studentid { get; set; }
        public string name{ get; set; }
    }

The project on which I am working is a .net web api project. 我正在处理的项目是.net Web api项目。 The post method I have written for the student is as below 我为学生写的发帖方法如下

        try
        {
            using (var connection = new SqlConnection(connectionString))
            {
                connection.Open();

                using (var cmd = new SqlCommand())
                {
                    cmd.CommandType = System.Data.CommandType.Text;
                    cmd.CommandText = "insert into student (name) " +
                        "values (@name)";

                    cmd.Connection = connection;
                    cmd.Parameters.AddWithValue("@name", student.name);

                    cmd.ExecuteNonQuery();
                }
            }
        }
        catch (SqlException ex)
        {

            Debug.WriteLine(ex.Message);
        }

Here is my question. 这是我的问题。 How do I write my methods with taking the foreign key into account? 如何在考虑外键的情况下编写方法? I could not find any code examples. 我找不到任何代码示例。 All of them are for entity framework... 它们都是针对实体框架的。

For example to get all students and courses you can use: 例如,要获取所有学生和课程,可以使用:

[HttpGet]
public ActionResult<StudentViewModel> GetAllStudents()
{
        try
        {
            using (var connection = new SqlConnection(connectionString))
            {
                connection.Open();

                using (var cmd = new SqlCommand())
                {
                    cmd.CommandType = System.Data.CommandType.Text;
                    cmd.CommandText = "SELECT s.id, s.name, c.Name as courseName FROM Student s INNER JOIN Courses c on c.studentId = s.id";
                    cmd.Connection = connection;


                    SqlDataAdapter da = new SqlDataAdapter(cmd);

                    da.Fill(dataTable);
                    connection.Close();
                    da.Dispose();

                    //Fill result view model from dataTable which will contain all data which you want from DB. 
                }
            }
        }
        catch (SqlException ex)
        {
            //Log exception
        }
}

But this is only sample. 但这仅是示例。 In real world much better to split logic between action in the controller and business logic for getting data. 在现实世界中,最好在控制器的操作和业务逻辑之间分配逻辑以获取数据。 And to use object-relational mapping (ORM) like EntityFramework will save a lot of time. 并且使用像EntityFramework这样的对象关系映射(ORM)将节省大量时间。 And if you need to use custom query you will have possibility to do it. 并且,如果您需要使用自定义查询,则可以进行自定义查询。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在 C# DatagridView 中插入行,在表中使用外键连接到 MYSQL - Insert Row in C# DatagridView connected to MYSQL with foreign key in tables 如何创建具有复合键的表,其中每个成员都是其他表的外键成员 - How do I create a table that has a composite key each member of which is a foreign key member to other tables 如何显示具有外键的表格数据C# - How to display tables data having foreign key c# 我如何使用 api 密钥在 c# 中调用 API - How do i call an API in c# with a api key 用外键在C#中定义两个表 - Define two tables in c# with foreign key 如何编写Web Api单元测试,我应该从UserManager获取信息 - How do I write Web Api unit test which I should get info from the UserManager 如何在2个不同的Azure SQL数据库中的3个表中编写C#列表查询 - How do I write a C# list query accross 3 tables in 2 different Azure SQL Databases 如何从Fluent API中为外键设置onUpdate? - How do I set onUpdate for a foreign key from the Fluent API? 如何命名Web API控制器类的C#方法? - How do you name a C# method of a controller class which is a Web API? 我如何在Asp.Net MVC中使用Entity Framework和Web Api获取外键表数据 - How do i get foreign key table data using Entity Framework and Web Api in Asp.Net MVC
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM