efCore+Mysql+Net Core

1.首先新建一个空的Asp.net core项目

2.新建一个类    gj.cs

public class gj
    {
        // <summary>
        /// 主键
        /// </summary>
        public int id { get; set; }

        /// <summary>
        /// 标题
        /// </summary>
        public string method { get; set; }
        /// <summary>
        /// 内容
        /// </summary>
        public string text { get; set; }
    
        public string type { get; set; }
    }

3.添加数据库上下文类。

public class DbGj:DbContext
    {
        public DbSet<gj> gj { set; get; }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
            => optionsBuilder.UseMySQL(@"Server=localhost;database=testapp;uid=root;pwd=woshishui");
    }

4.添加控制器

public class GJController : Controller
    {
       
        public IActionResult Index()
        {
            using (var db = new DbGj())
            {
                var lis = db.Set<gj>().ToList();
                 return View(lis);
            }
         
        }
      
    }

5.视图

@model IEnumerable<CoreTest_1.Models.gj>

@{
    ViewData["Title"] = "Index";
}

<h1>Index</h1>

<p>
    <a asp-action="Create">Create New</a>
</p>
<table class="table">
    <thead>
        <tr>
            <th>
                @Html.DisplayNameFor(model => model.method)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.text)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.type)
            </th>
            <th></th>
        </tr>
    </thead>
    <tbody>
@foreach (var item in Model) {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.method)
            </td>
            @*<td>
                @Html.DisplayFor(modelItem => item.text)
            </td>*@
            <td>
                @Html.DisplayFor(modelItem => item.type)
            </td>
            <td>
                <a asp-action="Edit" asp-route-id="@item.id">Edit</a> |
                <a asp-action="Details" asp-route-id="@item.id">Details</a> |
                <a asp-action="Delete" asp-route-id="@item.id">Delete</a>
            </td>
        </tr>
}
    </tbody>
</table>

F5运行程序 (如图)

原文地址:https://www.cnblogs.com/ouyangkai/p/11383310.html