惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

酷 壳 – CoolShell
酷 壳 – CoolShell
雷峰网
雷峰网
H
Hackread – Cybersecurity News, Data Breaches, AI and More
Spread Privacy
Spread Privacy
H
Hacker News: Front Page
PCI Perspectives
PCI Perspectives
Webroot Blog
Webroot Blog
罗磊的独立博客
H
Heimdal Security Blog
TaoSecurity Blog
TaoSecurity Blog
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
大猫的无限游戏
大猫的无限游戏
月光博客
月光博客
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
Google Online Security Blog
Google Online Security Blog
Last Week in AI
Last Week in AI
美团技术团队
Help Net Security
Help Net Security
The Hacker News
The Hacker News
C
Cisco Blogs
T
The Blog of Author Tim Ferriss
J
Java Code Geeks
The Register - Security
The Register - Security
IT之家
IT之家
WordPress大学
WordPress大学
Jina AI
Jina AI
Recent Commits to openclaw:main
Recent Commits to openclaw:main
H
Help Net Security
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
T
Threat Research - Cisco Blogs
P
Proofpoint News Feed
NISL@THU
NISL@THU
爱范儿
爱范儿
The GitHub Blog
The GitHub Blog
Scott Helme
Scott Helme
V
Vulnerabilities – Threatpost
B
Blog
T
Tenable Blog
博客园 - 三生石上(FineUI控件)
T
The Exploit Database - CXSecurity.com
S
Security Affairs
小众软件
小众软件
Hacker News: Ask HN
Hacker News: Ask HN
Security Latest
Security Latest
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
W
WeLiveSecurity
A
Arctic Wolf
L
LINUX DO - 热门话题
Google DeepMind News
Google DeepMind News
M
MIT News - Artificial intelligence

博客园 - Ant

ASP.NET Core 项目简单实现身份验证及鉴权 使用iconfont图标 IIS调试ASP.NET Core项目 配置GitHub的SSH key Visual Studio连接Oracle数据库 Visual Studio Code 如何将新项目发布到GIT服务器 Xamarin踩坑经历 Abp项目中的领域模型实体类访问仓储的方法 在Abp中集成Swagger UI功能 发布以NLog作为日记工具的ASP.NET站点到IIS注意事项 Android Studio 简介及导入 jar 包和第三方开源库方[转] 解决jquery-ui-autocomplete选择列表被Bootstrap模态窗遮挡的问题 ORACLE存储过程创建失败,如何查看其原因 火狐通行证升级为Firefox Sync后,如何在多设备间同步书签等信息 (原创)通用查询实现方案(可用于DDD)[附源码] -- 设计思路 (原创)通用查询实现方案(可用于DDD)[附源码] -- 简介 利用Lambda获取属性名称 Entity Framework 6.0 源码解读笔记(一) [转]Sql server2005中如何格式化时间日期
EF6配合MySQL或MSSQL(CodeFirst模式)配置指引
Ant · 2015-02-10 · via 博客园 - Ant

一、新建一个解决方案,包含两个项目:EF6CodeFirstMySQL.Model(动态库项目),EF6CodeFirstMySQL.Tests(控制台应用)

二、通过NuGet将EntityFramework6及MySql.Data.Entity包引入解决方案(两个项目都要引入)

三、在Model项目中添加三个类,BaseBill,Contract,DeliveryNote,后面两个类从BaseBill类继承。(代码参见附件)

四、在Model项目中添加DataModelContext类,继承自DbContext

    public class DataModelContext : DbContext
    {
        public DataModelContext()
            : base("DataModelContext")//web.config中connectionstring的名字
        {
        }

        public DbSet<Contract> Contracts { get; set; }
        public DbSet<DeliveryNote> DeliveryNotes { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            //指定单数形式的表名
            modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
            //物理表名添加xx前綴
            modelBuilder.Types().Configure(f => f.ToTable("xx" + f.ClrType.Name));
        }
    }

DataModelContext

五、在Model项目中添加DataModelInitializer类,用于初始化数据库中的数据

    public class DataModelInitializer : DropCreateDatabaseIfModelChanges<DataModelContext> // CreateDatabaseIfNotExists<DataModelContext>
    {
        protected override void Seed(DataModelContext context)
        {
            var contracts = new List<Contract>
            {
                new Contract{ BillNo = "PO20150201-001", BillDate=new DateTime(2015,  2,  1), TotalPrice=9876543.21M, Supplier = "Microsoft"},
                new Contract{ BillNo = "PO20141230-088", BillDate=new DateTime(2014, 12, 30), TotalPrice=1234567.89M, Supplier = "Oracle"},
            };
            context.Contracts.AddRange(contracts);
            context.SaveChanges();//可以分次提交,也可以最后一次性提交给数据库

            var deliveries = new List<DeliveryNote>
            {
                new DeliveryNote{ BillNo = string.Format("DN{0:yyyyMMdd}-006", DateTime.Today), TotalPrice=445566M, Contract=contracts.First(), Checker="张三"},
            };
            context.DeliveryNotes.AddRange(deliveries);
            context.SaveChanges();//可以分次提交,也可以最后一次性提交给数据库
        }

    }

DataModelInitializer

六、编辑app.config配置文件(注意:实际使用的配置文件为应用程序项目中的app.config或web.config,动态库项目中的app.config在运行时不起作用)

<?xml version="1.0" encoding="utf-8"?>
<!--注意:此项目为动态库,所以此配置文件内容仅供作为范本使用,实际的WPF或ASP.NET项目可从此文件复制配置内容进行修改-->
<configuration>
  <configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>
  <!--MySQL启用下面一行-->
  <entityFramework codeConfigurationType="MySql.Data.Entity.MySqlEFConfiguration, MySql.Data.Entity.EF6">
  <!--SQL SERVER 启用下面一行-->
  <!--entityFramework-->
    <contexts>
      <!--通过设置disableDatabaseInitialization="true",可以禁止数据库初始化操作-->
      <context type="EF6CodeFirstMySQL.Model.DataModelContext,EF6CodeFirstMySQL.Model" disableDatabaseInitialization="false">
        <databaseInitializer type="EF6CodeFirstMySQL.Model.DataModelInitializer,EF6CodeFirstMySQL.Model"></databaseInitializer>
      </context>
    </contexts>
    <!--MySQL启用下面一段配置项-->
    <defaultConnectionFactory type="MySql.Data.Entity.MySqlConnectionFactory, MySql.Data.Entity.EF6">
      <parameters>
        <parameter value="v11.0" />
      </parameters>
    </defaultConnectionFactory>
    <!--SQL SERVER 启用下面一行-->
    <!--defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" /-->
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
      <provider invariantName="MySql.Data.MySqlClient" type="MySql.Data.MySqlClient.MySqlProviderServices, MySql.Data.Entity.EF6, Version=6.9.5.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d"></provider>
    </providers>
  </entityFramework>
  <connectionStrings>
    <!--MySQL启用下面一行-->
    <add name="DataModelContext" connectionString="Data Source=localhost;port=3306;Initial Catalog=EF6CodeFirstDemo;user id=root;password=123456;" providerName="MySql.Data.MySqlClient" />
    <!--SQL SERVER 启用下面一行,注意数据库文件路径中使用了|DataDirectory|宏变量,该变量只在ASP.NET项目中有效-->
    <!--add name="DataModelContext" connectionString="Data Source=.;database=EF6CodeFirstDemo;uid=sa;pwd=123456;AttachDBFilename=|DataDirectory|\XantFlowDB.mdf;" providerName="System.Data.SqlClient"/-->
  </connectionStrings>

  <system.data>
    <DbProviderFactories>
      <remove invariant="MySql.Data.MySqlClient" />
      <add name="MySQL Data Provider" invariant="MySql.Data.MySqlClient" description=".Net Framework Data Provider for MySQL" type="MySql.Data.MySqlClient.MySqlClientFactory, MySql.Data, Version=6.9.5.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d" />
    </DbProviderFactories>
  </system.data>
</configuration>

app.config

七、编辑Tests项目中的Program.Main()方法,从数据库中读取数据并在控制台显示

        static void Main(string[] args)
        {
            using(var ctx = new DataModelContext())
            {
                foreach (DeliveryNote dn in ctx.DeliveryNotes.Include("Contract"))
                {
                    Console.WriteLine(string.Format("送货单号:{0},送货日期:{1:yyyy-MM-dd},到货金额:{2:#0,000.00},合同编号:{3},供应商:{4},合同总金额:{5},合同总金额(直接属性):{6}",
                        dn.BillNo, dn.BillDate, dn.TotalPrice, dn.Contract.BillNo, dn.Contract.Supplier, dn.Contract.TotalPrice, dn.ContractTotalPrice));
                }
            }

            Console.WriteLine("\n\n按[回车]键退出...");
            Console.ReadLine();
        }

Main()

八、一切准备就绪,按F5,欢快的跑起来吧!

 如果程序运行不起来,请先检查app.config文件中ConnectionString的设置是否正确(例如MySQL服务器地址、端口),再检查MySQL服务是否已开启。

九、最后我们来查看一下自动生成的数据表结构及初始化时填充的数据

源代码已经托管到OSChina:http://git.oschina.net/xant77/EF6CodeFirstSimpleDemo

posted on 2015-02-10 12:32  Ant  阅读(2699)  评论()    收藏  举报