ef mysql code first_[EF]vs15+ef6+mysql code first方式

写在前面

前面有篇文章,尝试了db first方式,但不知道是什么原因一直没有成功,到最后也没解决,今天就尝试下code first的方式。

一个例子

步骤

Connector/Net 下载该文件,并安装(如果没安装,请先安装)

使用Nuget安装EF

使用Nuget安装mysql提供程序。

在上面的步骤完成后,修改web.config文件,内容如下:

注意entityFramework 节点,默认是不会有codeConfigurationType属性的,请添加。否则会出现下面的错误:Specified key was too long; max key length is 767 bytes

6d3a31b595f4b9c67a9092c11bdc094f.png

测试

实体类

usingSystem;usingSystem.Collections.Generic;usingSystem.ComponentModel.DataAnnotations;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;namespaceWolfy.Ef_MySql_CodeFirst

{public classProduct

{public int Id { set; get; }

[MaxLength(128)]public string Name { set; get; }

[MaxLength(128)]public string Category { set; get; }public decimal Price { set; get; }public DateTime CreateDate { set; get; }

}

}

插入信息

usingSystem;usingSystem.Collections.Generic;usingSystem.Data.Entity;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;namespaceWolfy.Ef_MySql_CodeFirst

{classProgram

{static void Main(string[] args)

{var dbContext = newMyContext();

IDatabaseInitializer dbInitializer = null;if(dbContext.Database.Exists())

{//如果数据库已经存在

dbInitializer = new DropCreateDatabaseIfModelChanges();

}else{//总是先删除然后再创建

dbInitializer = new DropCreateDatabaseAlways();

}//Database.SetInitializer(dbInitializer);

dbInitializer.InitializeDatabase(dbContext);

dbContext.Products.Add(new Product() { CreateDate = DateTime.Now.AddDays(1), Name = "南孚电池", Category = "生活用品", Price = 3});

dbContext.SaveChanges();

}

}

}

还有一个错误经常出现

Model compatibility cannot be checked because the database does not contain model metadata. Model compatibility can only be checked for databases created using Code First or Code First Migrations.

大概意思是:不能检查模型的兼容性,因为数据库不包含模型元数据。在使用code first或者code fisrt迁移进行数据库创建的时候需要检查模型的兼容性。

此时,虽然生成了表_migrationhistory,但是该表内容为空。

e2d22c5fe73087241d85bd1fa71e517a.png

这个时候可以将数据库删除,重新生成就可以解决。

1d8ba8b549fdf9c793c1485fed5dfcb6.png

其中表_migrationhistory为创建历史表。

27ea6ba939dd5dffcd0f7f4ccb1d41e8.png

Products表

f79f62e790ce5b7f375f96967ade5e5f.png

发现添加的数据中中文为乱码,这是因为mysql默认的字符集为latin

849108bd37db4dc3b76eef44cd1b0eeb.png

关于乱码的解决方案很多,你可以修改数据库的字符集,或者数据表的字符集。也可以这样,修改连接字符串:

总结

折腾了一上午,一个简单的demo出来了。

d3d43bb7bdce1a268eeb4d7a1f2fdd45.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值