资讯

精准传达 • 有效沟通

从品牌网站建设到网络营销策划,从策略到执行的一站式服务

CodeFirst如何搭建Asp.NetCore2.0网站-创新互联

这篇文章主要介绍CodeFirst如何搭建Asp.Net Core2.0网站,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!

十年的云城网站建设经验,针对设计、前端、开发、售后、文案、推广等六对一服务,响应快,48小时及时工作处理。成都全网营销推广的优势是能够根据用户设备显示端的尺寸不同,自动调整云城建站的显示方式,使网站能够适用不同显示终端,在浏览器中调整网站的宽度,无论在任何一种浏览器上浏览网站,都能展现优雅布局与设计,从而大程度地提升浏览体验。成都创新互联从事“云城网站设计”,“云城网站推广”以来,每个客户项目都认真落实执行。

一步步教大家如何搭建Asp.Net Core2.0网站,以下所有都是建立在.NETCore2.0环境已经搭建好

右键解决方案>新建项目>

选择Web>ASP.NETCoreWeb应用程序(.NET Core)

CodeFirst如何搭建Asp.Net Core2.0网站

选择Web应用程序,暂时不选择启用Docker,身份验证选择个人用户账户(会自动生成一系列和用户认证的代码)

CodeFirst如何搭建Asp.Net Core2.0网站

CodeFirst如何搭建Asp.Net Core2.0网站

随后生代码层次目录如下:

CodeFirst如何搭建Asp.Net Core2.0网站

其中会包含身份信息的相关实现,比如相关实体信息(user)之类的,如果想对扩展微软自动的生成的用户实体类,可在Models中的ApplicationUser下扩展,在此ApplicationUser中添加属性即可:比如添加叫WeChatId属性,添加后如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity;

namespace DotNetCore20.Web.Models
{
  // Add profile data for application users by adding properties to the ApplicationUser class
  public class ApplicationUser : IdentityUser
  {
    /// 
    /// 微信Id
    /// 
    public string WeChatId { get; set; }
  }
}

在之后生成运行并迁移,数据库的AspNetUsers中就会多出WeChatId 属性.

一:安装引用

nugnet恢复引用失效时,可在程序包管理控制台输入:

dotnet restore 即可

CodeFirst如何搭建Asp.Net Core2.0网站

会发现在恢复指令后在NuGet中会有一个Microsoft.VisualStudio.Web.CodeGeneration.Design的报错,信息如下:

已使用“.NETPortable,Version=v0.0,Profile=Profile259, .NETFramework,Version=v4.6.1”而不是项目目标框架“.NETCoreApp,Version=v2.0”还原了包“Microsoft.Composition 1.0.27”。这可能会导致兼容性问题

这个库是ASP.NET Core的代码生成工具。包含用于生成控制器和视图的dotnet-aspnet-codegenerator命令,暂时可先卸载,不影响项目运行.

对项目类库的引用有以下几种方式

1.Nuget去安装(官网https://www.nuget.org/packages/)

2.右键依赖项点击菜单中的添加引用

3.可在程序包管理控制台输入:Install-Package引用类库名称

4.可右键编辑csproj工程文件进行添加,然后执行dotnet restore


CodeFirst如何搭建Asp.Net Core2.0网站

二.创建实体程序集

右键解决方案>添加项目>

CodeFirst如何搭建Asp.Net Core2.0网站

首先创建抽象类,供Entity实体继承,主要为每个实体提供公用属性

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Runtime.Serialization;
using System.Text;

namespace DotNetCore20.Entity.Core
{
  /// 
  /// DB表基底
  /// 
  [Serializable]
  public abstract partial class BaseEntity
  {
    /// 
    /// Id
    /// 
    [DataMember]
    public long Id { get; set; }

    /// 
    /// DB 資料版號
    /// 
    1607426098
    public byte[] RowVersion { get; set; }

    /// 
    /// 创建时间
    /// 
    [DataMember]
    public DateTime CreateTime { get; set; }

    /// 
    /// 更新时间
    /// 
    [DataMember]
    public DateTime UpdateTime { get; set; }

    /// 
    /// 状态
    /// 
    [DataMember]
    public EnumState State { get; set; }
  }

  /// 
  /// 状态
  /// 
  public enum EnumState
  {
    /// 
    /// 删除
    /// 
    Delete = 1,

    /// 
    /// 正常
    /// 
    Normal = 0,
  }
}

添加一个UserExtend用户扩展类(Entity):

using DotNetCore20.Entity.Core;
using System;
using System.Runtime.Serialization;

namespace DotNetCore20.Entity
{
  [DataContract]
  public class UserExtend : BaseEntity
  {
    /// 
    /// 用户Id
    /// 
    [DataMember]
    public long UserId { get; set; }

    /// 
    /// 昵称
    /// 
    [DataMember]
    public long NickName { get; set; }

  }
}

三.创建数据层

CodeFirst如何搭建Asp.Net Core2.0网站

添加引用

DAL层需要用到EF实体映射相关和我们自己前面定义的Entity中的UserExtend实体表,所以要添加相关引用,DotNetCore20.Entity和 Microsoft.EntityFrameworkCore.Tools

快捷键:Ctrl+Alt+o 打开程序包管理器输入以下:

install-package Microsoft.EntityFrameworkCore.Tools

CodeFirst如何搭建Asp.Net Core2.0网站

如果是网络限制下载失败,推荐把nuget镜像改为博客园资源,方法如下:

右键解决方案>管理解决方案的nuget程序包.显示如下:

CodeFirst如何搭建Asp.Net Core2.0网站

CodeFirst如何搭建Asp.Net Core2.0网站

新建一个数据上下文类,目录结构如下:

CodeFirst如何搭建Asp.Net Core2.0网站

DotNetCoreDbContext内部代码改为以下:

using DotNetCore20.Entity;
using Microsoft.EntityFrameworkCore;

namespace DotNetCore20.DAL.DbContext
{
  public class DotNetCoreDbContext : Microsoft.EntityFrameworkCore.DbContext
  {
    public DotNetCoreDbContext(DbContextOptions options) : base(options)
    {
    }
    public DbSet UserExtend { get; set; }
  }
}

在此基本的实体映射相关的代码都完毕,现在还有一步,就是数据库连接字符串的配置

首先打开appsettings.json文件,在ConnectionStrings节点下增加以下

复制代码 代码如下:

"DotNetCoreConnection": "Server=(localdb)\\mssqllocaldb;Database=DotNetCoreDb;Trusted_Connection=True;MultipleActiveResultSets=true"

增加后如下:

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=DotNetCoreDefaultDb;Trusted_Connection=True;MultipleActiveResultSets=true",
    "DotNetCoreConnection": "Server=(localdb)\\mssqllocaldb;Database=DotNetCoreDb;Trusted_Connection=True;MultipleActiveResultSets=true"
  },
 "Logging": {
  "IncludeScopes": false,
  "Debug": {
   "LogLevel": {
    "Default": "Warning"
   }
  },
  "Console": {
   "LogLevel": {
    "Default": "Warning"
   }
  }
 }
}

再打开web网站下的Startup文件,在ConfigureServices方法中添加一下行:

//自定义数据库连接字符串
services.AddDbContext(options =>
 options.UseSqlServer(Configuration.GetConnectionString("DotNetCoreConnection")));

增加后如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using DotNetCore20.Web.Data;
using DotNetCore20.Web.Models;
using DotNetCore20.Web.Services;
using DotNetCore20.DAL.DbContext;

 
namespace DotNetCore20.Web
{
  public class Startup
  {
    public Startup(IConfiguration configuration)
    {
      Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
      services.AddDbContext(options =>
        options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

      //自定义数据库连接字符串
      services.AddDbContext(options =>
        options.UseSqlServer(Configuration.GetConnectionString("DotNetCoreConnection")));

      services.AddIdentity()
        .AddEntityFrameworkStores()
        .AddDefaultTokenProviders();

      // Add application services.
      services.AddTransient();
      services.AddTransient();

      services.AddMvc();
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
      if (env.IsDevelopment())
      {
        app.UseDeveloperExceptionPage();
        app.UseBrowserLink();
        app.UseDatabaseErrorPage();
      }
      else
      {
        app.UseExceptionHandler("/Home/Error");
      }

      app.UseStaticFiles();

      app.UseAuthentication();

      app.UseMvc(routes =>
      {
        routes.MapRoute(
          name: "default",
          template: "{controller=Home}/{action=Index}/{id?}");
      });
    }
  }
}

运行程序,点击登陆(只要访问数据库的操作都可),出现错误页面:

CodeFirst如何搭建Asp.Net Core2.0网站

点击应用迁移CodeFirst如何搭建Asp.Net Core2.0网站,即自动迁移数据库.

由于两个数据库,只会自动迁移关于用户的表AspNetUsers,

所以还得VS中程序包管理器中下命令迁移.

Add-Migration firstMigration -Context DotNetCoreDbContext

以上命令执行后再执行以下命令:

Update-Database -ContextDotNetCoreDbContext;

然后查看数据库会发现多出两个数据库,

以DotNetCoreDefaultDb生成的为例,会生成如下表:

CodeFirst如何搭建Asp.Net Core2.0网站

其中AspNetUsers就中会有之前添加的WeChatId字段

CodeFirst如何搭建Asp.Net Core2.0网站

然后再次运行程序:

CodeFirst如何搭建Asp.Net Core2.0网站

这样一个完整的Asp.NetCore2.0网站就初步运行起来了

以上是“CodeFirst如何搭建Asp.Net Core2.0网站”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注创新互联行业资讯频道!


分享标题:CodeFirst如何搭建Asp.NetCore2.0网站-创新互联
文章链接:http://cdkjz.cn/article/dsgejo.html
多年建站经验

多一份参考,总有益处

联系快上网,免费获得专属《策划方案》及报价

咨询相关问题或预约面谈,可以通过以下方式与我们联系

大客户专线   成都:13518219792   座机:028-86922220