.net core Webapi +EF

Development Tools Vs2017 + MSsqlsever

Open the VS2017, a new web project

 

Click OK, build the project, increasing the Model folder in the project, an increase in the Model class TodoItem

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

Class TodoContext increase in the Model, for interacting with a database

1  public class TodoContext : DbContext
2     {
3         public TodoContext(DbContextOptions<TodoContext> options)
4             : base(options)
5         {
6         }
7 
8         public DbSet<TodoItem> TodoItems { get; set; }
9     }
View Code

Open appsettings.json, the configuration database connection string

{
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "TodoContext": "Server=.;Database=WebApiDemo;Trusted_Connection=True;MultipleActiveResultSets=true"
  }

}

In Startup, find ways ConfigureServices registration services registered in the database context and specify the database to sqlserver

 public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<Models.TodoContext>(opt =>
             opt.UseSqlServer(Configuration.GetConnectionString("TodoContext")));  //使用SqlServer数据库

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
        }

Thus, the basic configuration has been completed, and now with codefirst EF way to create a database, through the tool - "NuGet Package Manager -" Package Manager Console to bring up the console

Command is as follows:

Add-Migration Initial
Update-Database

  Now the database has been set up is completed

 

Next we add TodoController folder in Control 

 [Route("api/[controller]")]
    [ApiController]
    public class TodoController : ControllerBase
    {
        private readonly TodoContext _context;

        public TodoController(TodoContext context)
        {
            _context = context;

            if (_context.TodoItems.Count() == 0)
            {
                // Create a new TodoItem if collection is empty,
                // which means you can't delete all TodoItems.
                _context.TodoItems.Add(new TodoItem { Name = "Item1" });
                _context.SaveChanges();
            }
        }

        // GET: api/Todo
        [HttpGet]
        public async Task<ActionResult<IEnumerable<TodoItem>>> GetTodoItems()
        {
            return await _context.TodoItems.ToListAsync();
        }

        // GET: api/Todo/5
        [HttpGet("{id}")]
        public async Task<ActionResult<TodoItem>> GetTodoItem(long id)
        {
            var todoItem = await _context.TodoItems.FindAsync(id);

            if (todoItem == null)
            {
                return NotFound();
            }

            return todoItem;
        }
    }

  At this point, the whole Api project has been set up is completed, we can now verify OK

See call API, we have been successful return value, then we talk a common Post and Get, and parameter passing thing

Guess you like

Origin www.cnblogs.com/NotLaterforever/p/11480341.html