Asp.net core中Migration工具使用的交流分享

一、文章参数

  • 开发工具:

    visual studio 2015 community update 3 + .net core tools(preview2) + sqlserver2012 express

  • 开发环境:

    win10(版本14393)+ .net core(版本 1.0.0-preview2-003121)

  • 项目名称:

    AirMusic

  • 项目模板:

    Asp.net core WebApi(这里不用mvc模板,是因为mvc模板初始的内容太多,这里用不到)

  • AirMusic源码地址:

    https://github.com/boomyao/Blogs

二、开篇碎语

记得去年第一次做项目,用了asp.net mvc5,因此也第一接触了EntityFramework(版本是EF6)。 现在打算用asp.net core来完成一个项目,air music是学习asp.net core时新建的demo项目,以后学习core中遇到的一些问题一般会从这个项目产生,今天这篇文章是在migration初始化数据库时发生的一些问题。

三、主要内容

1、初始化的实体模型

public class Song

    {

        public int Id { get; set; }

        [Required]

        public string SongName { get; set; }

        public virtual ICollection<ArtistSong> Artists { get; set; }

        public virtual ICollection<SongListSong> SongLists { get; set; }

    }


    //歌手

    public class Artist

    {

        public int Id { get; set; }

        [Required]

        public string Name { get; set; }

        public virtual ICollection<Album> Albums { get; set; }

        public virtual ICollection<ArtistSong> Songs { get; set; }

    }


    //song with artist n:n table

    public class ArtistSong

    {

        [Key]

        public int ArtistId { get; set; }

        [Key]

        public int SongId { get; set; }

    }



    //专辑

    public class Album

    {

        public int Id { get; set; }

        [Required]

        public string Title { get; set; }

        public virtual ICollection<Song> Songs { get; set; }

    }


    //歌单

    public class SongList

    {

        public int Id { get; set; }

        [Required]

        public string Title { get; set; }

        public string Describe { get; set; }

        public virtual ApplicationUser User { get; set; }

        public virtual ICollection<SongListSong> Songs { get; set; }

    }


    // song with songlist n:n table

    public class SongListSong

    {

        [Key]

        public int SongListId { get; set; }

        [Key]

        public int SongId { get; set; }

    }


Store Models

2、引用EFcoore相关的Nuget包

  • "Microsoft.AspNetCore.Identity.EntityFrameworkCore": "1.0.0"

    (依赖了好多ef重要组件)

  • "Microsoft.EntityFrameworkCore.Tools": "1.0.0-preview2-final"

    (引用了才可以试用migration)

  • "Microsoft.EntityFrameworkCore.SqlServer": "1.0.0"

    (我觉得是ef连接sqlserver的必须组件)

还有就是必须在project.json里的tools节点中添加"Microsoft.EntityFrameworkCore.Tools": "1.0.0-preview2-final",不然输入命令”Add Migration“时就会报出下面这句错误。

"No parameterless constructor………“这句错误是因为ApplicationDbContext(数据库上下文类)没有写下面这个构造函数报的错误。

public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
{
}

 

3、配置数据库连接

Webapi模板已经创建好了appsetting.json文件,这个文件的作用和web.config是一样的

 

4、文章包袱:Migration过程中遇到的问题

在ApplicationDbContext重写的方法OnModelCreating中,有一行代码

base.OnModelCreating(builder)

当我把这行代码注释掉时,迁移过程中就会报出如下错误:

很明显,错误发生的原因是IdentityUser没有被映射到ApplicationDbContext,所以可以知道这句代码的作用,就是用来映射Identity的几个实体类的,没有这句,数据库中就不会自动生成Users、Roles……等Table了,一个让我很困惑的问题在进行第一次Migration时出现了。AirMusic的实体中,有这样一种关系:

但是神奇的事情发生了(我不想这样的):

migrationBuilder.CreateTable(

                name: "ArtistSongs",

                columns: table => new

                {

                    ArtistId = table.Column<int>(nullable: false),

                    SongId = table.Column<int>(nullable: false),

                    //ArtistId1 = table.Column<int>(nullable: true)

                },

                constraints: table =>

                {

                    table.PrimaryKey("PK_ArtistSongs", x => new { x.ArtistId, x.SongId });

                    table.ForeignKey(

                        name: "FK_ArtistSongs_Artists_ArtistId",

                        column: x => x.ArtistId,

                        principalTable: "Artists",

                        principalColumn: "Id",

                        onDelete: ReferentialAction.Cascade);

                    //table.ForeignKey(

                    //    name: "FK_ArtistSongs_Artists_ArtistId1",

                    //    column: x => x.ArtistId1,

                    //    principalTable: "Artists",

                    //    principalColumn: "Id",

                    //    onDelete: ReferentialAction.Restrict);

                    table.ForeignKey(

                        name: "FK_ArtistSongs_Songs_SongId",

                        column: x => x.SongId,

                        principalTable: "Songs",

                        principalColumn: "Id",

                        onDelete: ReferentialAction.Cascade);

                });


            migrationBuilder.CreateTable(

                name: "SongListSongs",

                columns: table => new

                {

                    SongListId = table.Column<int>(nullable: false),

                    SongId = table.Column<int>(nullable: false),

                    //SongListId1 = table.Column<int>(nullable: true)

                },

                constraints: table =>

                {

                    table.PrimaryKey("PK_SongListSongs", x => new { x.SongListId, x.SongId });

                    table.ForeignKey(

                        name: "FK_SongListSongs_Songs_SongId",

                        column: x => x.SongId,

                        principalTable: "Songs",

                        principalColumn: "Id",

                        onDelete: ReferentialAction.Cascade);

                    table.ForeignKey(

                        name: "FK_SongListSongs_SongLists_SongListId",

                        column: x => x.SongListId,

                        principalTable: "SongLists",

                        principalColumn: "Id",

                        onDelete: ReferentialAction.Cascade);

                    //table.ForeignKey(

                    //    name: "FK_SongListSongs_SongLists_SongListId1",

                    //    column: x => x.SongListId1,

                    //    principalTable: "SongLists",

                    //    principalColumn: "Id",

                    //    onDelete: ReferentialAction.Restrict);

                });


初次Migration中发生意外的代码(注释的那些)

自动添加了带artist1songlist1的字段,我很希望知道的朋友告诉我解决的办法!!我实在不知道怎么让EF不自动添加这个多余的字段,所以我把那些多余的字段都注释掉后,才update-database到数据库:

song-artist[N:N] , song-songlist[N:N]

在ApplicationDbContext的OnModelCreating方法里,可以手动的配置数据库中的关系,像什么组合主键啦,组合外键啦等等各种约束,都可以 实现。特别是数据库中实体的关系配置(1:1,1:N,N:N),例如:用方法builder.HasOne().WithMany()就可以建立[1:N]的关系。AirMusic初次Migration中,我也手动的配置了一些关系:

var entityAS=builder.Entity<ArtistSong>();

            entityAS.HasKey("ArtistId", "SongId");

            entityAS.HasOne<Artist>()

                .WithMany()

                .HasForeignKey("ArtistId");


            var entitySS = builder.Entity<SongListSong>();

            entitySS.HasKey("SongListId", "SongId");

            entitySS.HasOne<SongList>()

                .WithMany()

                .HasForeignKey("SongListId");

上面代码的作用是,ArtistId和SongId设为ArtistSong的组合主键,ArtistSong的ArtistId设为Artist的外键。entitySS的作用也大致相同。

四、篇后总结

第一次完整的写一篇博文,晚上去吃饭是电脑自动重启更新了,vscode里的代码都没保存,打开博客园文章管理发现什么都没了,难过的就去听歌睡觉了。第二天起来打算从新来过时,发现有一行“自动保存恢复”,那个感觉就和中了100块的彩票一样。

希望有人看完这篇文章吧,新写手最需要的就是多给建议呀!谢谢

原文地址:http://www.cnblogs.com/boomyao/p/5745525.html


.NET社区新闻,深度好文,微信中搜索dotNET跨平台或扫描二维码关注

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/328796.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

BigDecimal类的使用

BigDecimal类的使用 一般常用的数据类型int和double类型但是在项目中我们会使用到大整数的处理类BigDecimal类 它有着自己的加减乘除和比较大小的方法 一、BigDecimal加减乘除的使用 1.加法 BigDecimal num1 new BigDecimal("10"); BigDecimal num2 new BigDe…

经典台词

内容来源&#xff1a;网络&#xff0c;侵删 01.满桌佳肴&#xff0c;你得有好牙&#xff1b;腰缠万贯&#xff0c;你得有命花。 02.赏一路风光&#xff0c;你得走得动&#xff1b;拣一座金山&#xff0c;你得能够拿。 03.垄沟里刨食的是条好汉子&#xff0c;病床上数钱的是个傻…

看了牛客网要发博客才好找工作,发篇冷静一下

看了牛客网要发博客才好找工作&#xff0c;发篇冷静一下

深入浅出 JIT 编译器

转载自 深入浅出 JIT 编译器JIT 简介 JIT 是 just in time 的缩写, 也就是即时编译编译器。使用即时编译器技术&#xff0c;能够加速 Java 程序的执行速度。下面&#xff0c;就对该编译器技术做个简单的讲解。 首先&#xff0c;我们大家都知道&#xff0c;通常通过 javac 将程…

org.springframework.uti包下的StringUtils的使用和org.apache.commons.lang包下StringUtils的使用

一、org.springframework.util.StringUtils StringUtils常用方法描述boolean isEmpty(Object str)判断字符串是否为空&#xff0c;如果为nul或者""则返回true&#xff0c;否则返回falseboolean hasLength(CharSequence str)判断字符串是否有长度&#xff0c;字符串不…

ASP.NET Core依赖注入解读amp;使用Autofac替代实现

1. 前言 关于IoC模式&#xff08;控制反转&#xff09;和DI技术&#xff08;依赖注入&#xff09;&#xff0c;我们已经见过很多的探讨&#xff0c;这里就不再赘述了。比如说必看的Martin Fowler《IoC 容器和 Dependency Injection 模式》&#xff0c;相关资料链接都附于文章末…

Java 中的伪共享详解及解决方案

转载自 Java 中的伪共享详解及解决方案1. 什么是伪共享 CPU 缓存系统中是以缓存行&#xff08;cache line&#xff09;为单位存储的。目前主流的 CPU Cache 的 Cache Line 大小都是 64 Bytes。在多线程情况下&#xff0c;如果需要修改“共享同一个缓存行的变量”&#xff0c;就…

ServletActionContext.getRequest().getSession() 和 ActionContext.getContext().getSession()的区别

ServletActionContext.getRequest().getSession() 和 ActionContext.getContext().getSession() ActionContext.getContext().getSession(); 这个方法获取的session是struts封装过的一个Map类型的session&#xff0c;只能调用put()方法缓存数据。 ServletActionContext.getRe…

弯下腰,拾起你无价的尊严

内容来源于网络&#xff0c;侵删&#xff01; 很久以前&#xff0c;一位挪威青年男子漂洋过海到了法国&#xff0c;他要报考著名的巴黎音乐学院。 考试的时候&#xff0c;尽管他竭力将自己的水平发挥到最佳状态&#xff0c;但主考官还是没能录取他。 身无分文的青年男子来到学…

在离线环境中发布.NET Core至Windows Server 2008

0x00 写在开始 之前一篇博客中写了在离线环境中使用.NET Core&#xff0c;之后一边学习一边写了一些页面作为测试&#xff0c;现在打算发布一下试试。看了下官方给出的发布教程感觉挺详细的了&#xff08;https://docs.asp.net/en/latest/publishing/iis.html&#xff09;&…

输入一个英文句子,翻转句子中单词的顺序 例如输入“I am a student.”,则输出“student. a am I”。

package com.atguigu.java; //输入一个英文句子&#xff0c;翻转句子中单词的顺序&#xff0c;但单词内字符的顺序不变。句子中单词以空格符隔开。 //为简单起见&#xff0c;标点符号和普通字母一样处理。 //例如输入“I am a student.”&#xff0c;则输出“student. a am …

Java 父类子类的对象初始化过程

转载自 Java 父类子类的对象初始化过程摘要: Java基本的对象初始化过程&#xff0c;子类的初始化&#xff0c;以及涉及到父类和子类的转化时可能引起混乱的情况。1. 基本初始化过程&#xff1a;对于一个简单类的初始化过程是&#xff1a;static 修饰的模块&#xff08;static变…

HttpServletRequest中getAttribute()和getParameter()的区别

一、数据据来源不同 HttpServletRequest类有setAttribute()方法&#xff0c;而 没有setParameter()方法get/setParameter是在对你的页面中的表单元素进行操作&#xff0c;获取的是这个表单元素中的值&#xff0c;是某个表单提交过去的数据get/setAttribute是对你页面中自己定义…

使用VS Code开发调试.NET Core 多项目

使用Visual Studio Code(VS Code)开发调试.NET Core和ASP.NET Core 多项目multiple project。 之前讲解过如果使用Visual Studio Code(VS Code) 开发单个.NET Core和ASP.NET Core项目&#xff0c;大家也都知道如何开发。 多项目可能有些人还不大了解&#xff0c;今天给大家介绍…

git 在ssh情况下提交代码

git --version --git版本 用户目录&#xff08;~/&#xff09; vim ~/.gitconfig --编辑用户目录&#xff08;~/&#xff09;下的 .gitconfig文件 --输入i 进入编辑模式 [user] nameRosen email1091947832qq.com [alias] --配置别名 cocheckout 切换分…

如果你也会C#,那不妨了解下F#(1):F# 数据类型

简单介绍 F#&#xff08;与C#一样&#xff0c;念作“F Sharp”&#xff09;是一种基于.Net框架的强类型、静态类型的函数式编程语言。可以说C#是一门包含函数式编程的面向对象编程语言&#xff0c;而F#是一门包含面向对象的函数式编程语言。可以查看官方文档了解更多信息。 本系…

String path = request.getContextPath()和String basePath = request.getScheme()

在JSP当中我们会用此代码来拼接路径&#xff0c;所以此语句是用来拼装当前网页的相对路径的。 <% String path request.getContextPath(); String basePath request.getScheme()"://"request.getServerName()":"request.getServerPort()path"/&…

Java中的函数传递

转载自 Java中的函数传递在C和C中&#xff0c;函数的传递可以通过函数指针来实现。在C#中&#xff0c;函数传递可以通过委托、Action、Func来实现。Java中没有函数指针、没有委托&#xff0c;那函数要如何传递呢&#xff1f; 可以通过以下两种方式实现。 1、通过handler&#…

使用Nginx搭建图片服务器(windows7)

1.进入官网下载nginx压缩包&#xff0c;解压后目录如下 2.在解压后的conf/nginx.conf配置文件中&#xff0c;添加添加或者修改带有颜色地方的代码 #user nobody; worker_processes 1; #error_log logs/error.log; #error_log logs/error.log notice; #error_log logs/e…

配置mybatis-plus逻辑删除

一、在pom文件里导入依赖 <dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId><version>${mybatis.plus.boot.starter}</version> </dependency>二、在yml文件或者在properties…