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>
添加AccountUser类
1 using System; 2 using System.ComponentModel.DataAnnotations; 3 using System.ComponentModel.DataAnnotations.Schema; 4 5 namespace EFCodeFirst.Entity 6 { 7 [Table("user")] 8 public class AccountUser 9 { 10 /// <summary> 11 /// 用户ID 12 /// </summary> 13 [Column("ID")] 14 [Key] 15 public int AccountUserId { get; set; } 16 17 /// <summary> 18 /// 用户名 19 /// </summary> 20 public string Name { get; set; } 21 22 /// <summary> 23 /// 年龄 24 /// </summary> 25 public Nullable<int> Age { get; set; } 26 27 /// <summary> 28 /// 性别 29 /// </summary> 30 public Nullable<bool> Sex { get; set; } 31 32 } 33 }
注:特性“Table”指定数据库中与该实体产生映射的表名,默认不添加系统会去数据库中寻找表名为:“类名+s”的表,找不到会报错。
特性“Column”来指定映射表中的列名,如果属性名与列名相同,则不用添加,系统默认属性名与列名一致。
以上方式为Data Annotations模式(数据注解)映射数据库方法。
EF还提供Fluent API配置来映射数据库,下面会讲到。
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自带的数据库中
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数据库已经成功
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(); }
可以看到数据库中同时向省表和市表中添加了相关数据