Scaffold EF Core with Web API

Shabbir Daruwala 176 Reputation points
2021-10-07T11:13:26.6+00:00

Hi Everyone,

I have done Scaffold using EF Core using WEB Api controller now how can use this to build the cshtml in MVC Application.

Basically when we do Scaffold using EF Core with MVC Controller it automatically creates actionresult with create, detail ,delete and list along with chtml prepopulated HTML Code with model but we how can create or automatically build cshtml if we have Web API

Apologies let me know if it's not clear explained.

Thanks,
Shabbir

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,075 questions
{count} votes

Accepted answer
  1. Zhi Lv - MSFT 31,756 Reputation points Microsoft Vendor
    2021-10-08T07:35:02.697+00:00

    Hi @Shabbir Daruwala ,

    If the Web API controller and the MVC controller are in the same project, you could also use the Scaffold to generate the MVC controller and the related cshtml page.

    But, from your description, I assume the Web API controller and MVC application are in a different project. If that is the case, in the MVC application, you have to create the view model based on the API return data or required parameter, then based on the view model to create view page.

    Besides, you can put the class and the dbcontext in a separate Class Library, then add it in the API and MVC application, then based on the model to create action and view page. Like this:

    Here I create three projects: the class library contains all the class and the dbcontext

    138881-image.png

    Then, in the MVC and API application, I add the class library reference, and install the following package via Nuget:

    138859-image.png

    Then, add the connection string in the appsettings.json file and in the ConfigureService method, register the DbContext:

        public void ConfigureServices(IServiceCollection services)  
        {  
            services.AddDbContext<EFCoreLibraryContext>(options =>  
                 options.UseSqlServer(  
                     Configuration.GetConnectionString("DefaultConnection")));  
            services.AddControllersWithViews();  
        }  
    

    After that, I could use Scaffold adding the Controller and views:

    138844-image.png

    The result as below:

    138763-image.png


    If the answer is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,
    Dillion

    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Shabbir Daruwala 176 Reputation points
    2021-10-08T10:23:37.123+00:00

    Thanks ZhiLv-MSFT, I am doing exactly what you mention that's only way to scaffold.

    Thanks again

    0 comments No comments