ASP.NET Core MVC : fill data from SQL Server function into model

cs7cruho  于 2023-10-15  发布在  .NET
关注(0)|答案(1)|浏览(117)

I looked for a lot of training materials, but I couldn't find any real example for a database first approach when creating a simple CRUD web application in ASP.NET Core MVC.

In real life your database has meaningless foreign keys in tables, and I need to fill models from a view or function from SQL Server. All training materials are using a single table directly and doing CRUD on that one table but in real life for example I need to load options of a drop-down list from another table and show the title but update the value from other table's primary key.

Can anyone help with explaining how I can execute a query from SQL Server to use for example a table-valued function and load the data into my model in MVC architecture?

the function or application structure is not important because I am just starting to learn C# and ASP.NET Core but for my first example, I cannot find a way to connect my application to an existing SQL function or run a stored procedure when my user wants to edit something.

I apologize in advance if it is a stupid question, I am very new to web application programming.

I tried using a dbContext but I think it only recognizes the tables only when created from application first approach and doesn't know about function or views in the database.

mwecs4sa

mwecs4sa1#

As you said, the Scaffold-DbContext will not generate the model for the SP and table function.

So if you want to use it, one possible way is creating the data model by yourself and using the FromSql method to call it.

Like this:

var context = new SchoolContext(); 
var param = new SqlParameter("@FirstName", "Bill");
var students = context.Students.FromSql("GetStudents @FirstName", param).ToList();

More details, you could refer to this article .

相关问题