ASP.NET Core WebApi + EF Core (CRUD implemented using Swagger test API)

EF has two different versions, namely Entity Framework Core and Entity Framework 6

EF Core: lightweight, extensible, cross-platform, reference EF6, a new platform, a small learning curve, introduce some new features ( bulk deletion )

EF 6: heavy, stable, and Microsoft has no intention to carry out a large version of the upgrade can not be cross-platform.

 

How to achieve EFCore function

1. Create ASP.NET Core Web Application 

 

 

 

 

2, the new class TodoItem

  First, create a new folder> Models

  Add TodoItem in class Models

1 public class TodoItem
2     {
3         public long Id { get; set; }
4         public string Name { get; set; }
5         public bool IsComplete { get; set; }
6     }

3. Add the database context

  Select Management NuGet package

      

  Select "Browse" tab, and then enter in the search box Microsoft.EntityFrameworkCore.SqlServer .

  Select "Microsoft.EntityFrameworkCore.SqlServer" in the left pane.

  Select the right pane of the "project" check box, and then select "Install."

  Using the above described added again Microsoft.EntityFrameworkCore.InMemory NuGet package

  After two NuGet installation is complete, then a new class Models in TodoContext

public class TodoContext : DbContext
    {
        public TodoContext(DbContextOptions<TodoContext> options)
            : base(options)
        {
        }

        public DbSet<TodoItem> TodoItems { get; set; }
    }

4, registration database context

  Sqlserver to create a database connection statement in the startup configuration file appsettings.json

  "ConnectionStrings": {
    "todoContext": "server=.;database=TodoDatas;uid=sa;pwd=123456"
  }

  Go to the Startup class that implements the constructor Startup class registration database context ConfigureServices

public  class the Startup 
    { 
        public the Startup (IConfiguration Configuration) 
        { 
            the Configuration = Configuration; 
        } 
        public IConfiguration the Configuration { GET ;}
         // This method is called at run time.
        // You can use this method to add service to a container such as ASP.NET Core MVC, Entity Framework Core and the Identity 
         // For more information about configuring the application, you can view https://go.microsoft.com/fwlink/? = 398.94 thousand the LinkID 
        public  void ConfigureServices (IServiceCollection Services) 
        { 
            // use sqlserver database
            services.AddDbContext <TodoContext> (opt => 
               opt.UseSqlServer (Configuration.GetConnectionString ( " todoContext " ))); 
            services.AddControllers (); 
            services.AddMvcCore (); 
        } 

        // This method is invoked at run time
         // can using this method to configure the HTTP request pipeline / pipeline for defining middleware request 
        public  void the configure (App IApplicationBuilder, IWebHostEnvironment the env) 
        { 
            IF (env.IsDevelopment ()) 
            { 
                app.UseDeveloperExceptionPage (); 
            } 

            app.UseRouting () ; 

            app.UseEndpoints (Endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }

5, the installation migration package - generating a database (SQLServer) through code

  Open the Package Manager Console

  Input: Add-Migration InitDatabase

  Input: update-database to generate the database

6, adding a controller

  New Folder> Controllers

  Add TodoController controller Controllers in

namespace EFCoreTest.Controllers 
{ 
    // If the access path 404 needs to be configured for the route 
    [the Route ( " API / [Controller] " )] 
    [ApiController] 
    public  class TodoController: the Controller 
    { 
        Private  Readonly TodoContext _context;
         public TodoController (TodoContext context) 
        { 
            _context = context; IF (_context.TodoItems.Count () == 0 ) 
            { 
                // if the set is empty, then create a new TodoItem,
                 // which means you can't delete all TodoItems. _context.TodoItems.Add(new TodoItem { Name = "Item1" }); _context.SaveChanges(); 
                _context.TodoItems.Add(new TodoItem { Id = 1, Name = "Item1", IsComplete = false });
                _context.TodoItems.Add(new TodoItem { Id = 2, Name = "Item2", IsComplete = false });
                _context.TodoItems.Add(new TodoItem { Id = 3, Name = "Item3", IsComplete = true });
                _context.SaveChanges();
            }
        }

        [HttpGet]
        public IEnumerable<TodoItem> GetAll() 
        {
            return _context.TodoItems.ToList();
        }
    } 
}

  4.4 to access the page you need to set route

  Go launchSettings.json, adding "launchUrl": "api / Todo"

{
  "iisSettings": {
    "windowsAuthentication": false, 
    "anonymousAuthentication": true, 
    "iisExpress": {
      "applicationUrl": "http://localhost:54029",
      "sslPort": 44320
    }
  },
  "profiles": {
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "launchUrl": "api/Todo",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "EFCoreTest": {
      "commandName": "Project",
      "launchBrowser": true,
      "applicationUrl": "https://localhost:5001;http://localhost:5000",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
}

7, CRUD

namespace EFCoreTest.Controllers 
{ 
    // If the access path 404 needs to be configured for the route 
    [the Route ( " API / [Controller] " )] 
    [ApiController] 
    public  class TodoController: the Controller 
    { 
        Private  Readonly TodoContext _context;
         public TodoController (TodoContext context) 
        { 
            _context = context;
             IF (_context.TodoItems.Count () == 0 ) 
            { 
                // if the set is empty, then create a new TodoItem,
                 // which means you can't delete all TodoItems. _context.TodoItems.Add(new TodoItem { Name = "Item1" }); _context.SaveChanges(); 
                _context.TodoItems.Add(new TodoItem { Name = "Item1", IsComplete = false });
                _context.TodoItems.Add(new TodoItem { Name = "Item2", IsComplete = false });
                _context.TodoItems.Add(new TodoItem { Name = "Item3", IsComplete = true });

                _context.SaveChanges();
            }
        }

        [HttpGet]
        public IEnumerable<TodoItem> GetAll()
        {
            return _context.TodoItems.ToList();
        }

        /// <summary>
        /// 根据Id查找数据
        /// </summary>
        /// <param name="Id">序号</param>
        /// <returns></returns>
        [HttpGet("{Id}", Name = "GetTodo")]
        public async Task<TodoItem> GetByID(int Id)
        {
            var item = await _context.TodoItems.FirstOrDefaultAsync(t => t.Id == Id);

            return item;
        }

        /// <summary>
        /// 创建
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Create([FromBody] TodoItem item)
        {
            if (item == null)
            {
                return BadRequest();
            }
            else
            {
                _context.TodoItems.Add(item);
                await _context.SaveChangesAsync();
                return Ok(item);
            }
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="Id"></param>
        /// <param name="item"></param>
        /// <returns></returns>
        [HttpPut("{id}")]
        public async Task<IActionResult> Update(int id, [FromBody] TodoItem item)
        {
            if (item == null)
            {
                return BadRequest();
            }
            else
            {
                var todo = _context.TodoItems.SingleOrDefault(t => t.Id == id);

                if (todo == null)
                {
                    return NotFound();
                }
                else
                {
                    todo.IsComplete = item.IsComplete;
                    todo.Name = item.Name;

                    _context.TodoItems.Update(todo);
                    await _context.SaveChangesAsync();

                    return Ok(todo);
                }

            }
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        [HttpDelete("{Id}")]
        public async Task<IActionResult> Delete(int Id)
        {
            var todo = _context.TodoItems.SingleOrDefault(t => t.Id == Id);

            if (todo == null)
            {

                return NotFound();
            }
            else
            {
                _context.TodoItems.Remove(todo);
                await _context.SaveChangesAsync();

                return Ok();
            }
        }
    }
}

  Operating results show

8, using a swagger

  Swagger both the API documentation management and test functions

  Open the Package Manager Console

  输入:Install-Package Swashbuckle.AspNetCore

  After successful installation to Startup type, to swagger middle added to the request pipeline, the need to add swaggergen method ConfigureServices method startup class,

  To enable this middleware, we also need to call useswagger method Configure method startup class.

public  class the Startup 
    { 
        public the Startup (IConfiguration Configuration) 
        { 
            the Configuration = Configuration; 
        } 
        public IConfiguration the Configuration { GET ;}
         // This method is called at run time.
        // You can use this method to add service to a container such as ASP.NET Core MVC, Entity Framework Core and the Identity 
         // For more information about configuring the application, you can view https://go.microsoft.com/fwlink/? = 398.94 thousand the LinkID 
        public  void ConfigureServices (IServiceCollection Services) 
        { 
            // use sqlserver database
            services.AddDbContext<TodoContext>(opt =>
               opt.UseSqlServer(Configuration.GetConnectionString("todoContext")));
            services.AddControllers();
            services.AddMvcCore();

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
            });

        method may be used to configure the HTTP request pipeline / pipeline for definition request middleware//This method is called at run time
        //
        }
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseSwagger();

            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
            });

            app.UseRouting();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }

  Enter the path: HTTPS: // localhost: 44320 / Swagger / index.html

  Show results

  Source Download: https: //pan.baidu.com/s/1oJbjC4ph8zJIkAujUExDzQ extraction code: meyl

  Attached PDF Development Guide

  Follow-up will continue to update other information, like please pay attention to Oh! .

 

Guess you like

Origin www.cnblogs.com/duhaoran/p/12661570.html
Recommended