在netcore2.1中使用mysql

      在netcore2.1中使用mysql已关闭评论

编辑*.csproj文件

加入

<ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.All" Version="2.1.2" />
    <PackageReference Include="Pomelo.EntityFrameworkCore.MySql" Version="2.1.1" />
  </ItemGroup>

还原nuget或者使用nuget安装上述类库

进入*.csproj所在目录,运行如下命令

 dotnet ef dbcontext scaffold "server=数据库连接字符串;" "Pomelo.EntityFrameworkCore.MySql"

成功的话,会在当前目录生成表实体

netcore对数据库的支持请参见 https://docs.microsoft.com/zh-cn/ef/core/providers/

在startup.cs中添加如下代码

 public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<RuiJiContext>(options => options.UseMySql(Configuration.GetConnectionString("ruijiMysql"),
                        mysqlOptions =>
                        {
                            mysqlOptions.ServerVersion(new Version(5, 7, 23), ServerType.MySql);
                        }
                ));

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            #region addrepository
            services.AddTransient<UserRepository>();
            services.AddTransient<UserLoginLogRepository>();
            services.AddTransient<TicketRepository>();
            services.AddTransient<ProductRepository>();
            #endregion
        }

调用如下

public class ProductRepository
    {
        private readonly RuiJiContext _context;

        public ProductRepository(RuiJiContext context)
        {
            _context = context;
        }

        public List<Product> GetModels(string local)
        {
            var db = _context.Product.Where(p => p.Local == local);
            return db.ToList();
        }
    }

 

 

© 2018, RuiJi 社区. 版权所有.转载请注明出处