Net EF框架+ MySql示例

640?wx_fmt=jpeg


1.nuget中添加包EF和MySql.Data.Entity

2.config文件添加如下配置

1.配置entitframework节点(一般安装EF时自动添加)

 <entityFramework>

    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">

      <parameters>

        <parameter value="mssqllocaldb" />

      </parameters>

    </defaultConnectionFactory>

    <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.9.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d"></provider>

    </providers>

  </entityFramework>

  2.配置system.data节点(一般安装MySql.Data.Entity时自动添加)

  <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.9.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d" />

    </DbProviderFactories>

  </system.data>

 3.添加连接串节点(以实际情况修改库名、密码等属性)

 <connectionStrings>

    <add name="MyContext" connectionString="Data Source=localhost;port=3306;Initial Catalog=aceadmin;user id=root;password=xxx;" providerName="MySql.Data.MySqlClient" />

  </connectionStrings>

3.添加实体类

添加AccountUser类

using System;

using System.ComponentModel.DataAnnotations;

using System.ComponentModel.DataAnnotations.Schema;


namespace EFCodeFirst.Entity

{

    [Table("user")]

    public class AccountUser

    {

        /// <summary>

        /// 用户ID

        /// </summary>

        [Column("ID")]

        [Key]

        public int AccountUserId { get; set; }


        /// <summary>

        /// 用户名

        /// </summary>

        public string Name { get; set; }


        /// <summary>

        /// 年龄

        /// </summary>

        public Nullable<int> Age { get; set; }


        /// <summary>

        /// 性别

        /// </summary>

        public Nullable<bool> Sex { get; set; }


    }

}

注:特性“Table”指定数据库中与该实体产生映射的表名,默认不添加系统会去数据库中寻找表名为:“类名+s”的表,找不到会报错。


特性“Column”来指定映射表中的列名,如果属性名与列名相同,则不用添加,系统默认属性名与列名一致。


以上方式为Data Annotations模式(数据注解)映射数据库方法。


EF还提供Fluent API配置来映射数据库,下面会讲到。

4.添加Context实体对象

using System.Data.Entity;


namespace EFCodeFirst

{

    public class DContext : DbContext

    {

        /// <summary>

        /// 添加构造函数,name为config文件中数据库连接字符串的name

        /// </summary>

        public DContext() : base("name=MyContext")

        {


        }


        #region 数据集

        public DbSet<AccountUser> AccountUsers { get; set; }


        #endregion  

    }

}

定义新的上下文类DContext集成DbContext


这里声明了与数据库映射的对象AccountUser,以后可以直接用属性AccountUsers来进行对数据库的操作


注:一定要添加构造函数并指明config文件中数据库连接字符串的name,否则系统将把数据库默认指定到VS自带的数据库中

5.测试简单的插入数据

class Program

    {

        static void Main(string[] args)

        {

            try

            {

                var user = new AccountUser()

                {

                    Name = "Test",

                    Sex = true,

                    Age = 29

                };

                using (var context = new DContext())

                {

                    context.AccountUsers.Add(user);

                    context.SaveChanges();

                    var accountUsers = context.AccountUsers.ToList();

                }

                Console.Write("{0}", user.AccountUserId);

            }

            catch (Exception ex)

            {

                Console.Write("{0}", ex);

            }

            Console.ReadLine();

        }

    }

至此EF框架连接MySql数据库已经成功

6.使用Fluent API配置EF映射关系

1.添加新类省、市

public class Provice

    {

        /// <summary>

        /// 省份ID

        /// </summary>

        public int ProviceId { get; set; }


        /// <summary>

        /// 省份名

        /// </summary>

        public string ProviceName { get; set; }


        /// <summary>

        /// 省份下城市

        /// </summary>

        public List<City> Citys { get; set; }

    }


    public class City

    {

        /// <summary>

        /// 城市ID

        /// </summary>

        public int CityId { get; set; }


        /// <summary>

        /// 所属省份ID

        /// </summary>

        public int ProviceId { get; set; }


        /// <summary>

        /// 城市名称

        /// </summary>

        public string CityName { get; set; }


        /// <summary>

        /// 所属城市

        /// </summary>

        public Provice ProviceData { get; set; }

    }

2.添加Fluent API配置类,继承自EntityTypeConfiguration对象

using System.Data.Entity.ModelConfiguration;


namespace EFCodeFirst

{

    public class ProviceConfiguration : EntityTypeConfiguration<Provice>

    {

        public ProviceConfiguration()

        {

            ToTable("provice")                                                  //映射表

                .HasKey(q => q.ProviceId)                                       //指定主键

                .HasMany(q => q.Citys).WithRequired(q => q.ProviceData).HasForeignKey(q => q.ProviceId);        //配置一对多关系

        }

    }

}

注:由于这里添加了外键,则必须用WithRequired方法而不能用WithOption方法,否则报错

using System.Data.Entity.ModelConfiguration;


namespace EFCodeFirst

{

    public class CityConfiguration : EntityTypeConfiguration<City>

    {

        public CityConfiguration()

        {

            ToTable("city")

            .HasKey(q => q.CityId)

            .Property(q => q.ProviceId).IsRequired();

        }

    }

}

一对多关系只用在一端配置,provice处配置后不需要在city端再配置

3.将Fluent API配置添加到DContext类中,重写OnModelCreating方法

public class DContext : DbContext

    {

        /// <summary>

        /// 添加构造函数,name为config文件中数据库连接字符串的name

        /// </summary>

        public DContext() : base("name=MyContext")

        {


        }


        #region 数据集

        public DbSet<AccountUser> AccountUsers { get; set; }

        public DbSet<Provice> Provices { get; set; }

        public DbSet<City> Citys { get; set; }

        #endregion


        #region Fluent API配置

        protected override void OnModelCreating(DbModelBuilder modelBuilder)

        {

            modelBuilder.Configurations.Add(new ProviceConfiguration());

            modelBuilder.Configurations.Add(new CityConfiguration());

        }

        #endregion

    }

4.main方法中级联添加省、市

static void Main(string[] args)

        {

            try

            {

                var provice = new Provice

                {

                    ProviceName = "河南省",

                    Citys = new List<City>()

                    {

                        new City() { CityName = "安阳"},

                        new City() { CityName = "郑州"},

                        new City() { CityName = "洛阳"},

                    }

                };

                using (var context = new DContext())

                {

                    context.Provices.Add(provice);

                    context.SaveChanges();

                    var provices = context.Provices.Include("Citys").ToList();

                }

                Console.Write("{0}", provice.ProviceId);

            }

            catch (Exception ex)

            {

                Console.Write("{0}", ex);

            }


            Console.ReadLine();

        }

可以看到数据库中同时向省表和市表中添加了相关数据

7.EF的Data Annotations与Fluent API是可以同时使用的,但同效果的配置只需要在二者之一中配置就好。


原文地址:https://www.cnblogs.com/hgmyz/p/12352087.html