Net EF框架+ MySql示例
1.nuget中添加包EF和MySql.Data.Entity
2.config文件添加如下配置
1.配置entitframework節(jié)點(diǎn)(一般安裝EF時(shí)自動(dòng)添加)
?<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節(jié)點(diǎn)(一般安裝MySql.Data.Entity時(shí)自動(dòng)添加)
? <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.添加連接串節(jié)點(diǎn)(以實(shí)際情況修改庫(kù)名、密碼等屬性)
?<connectionStrings>
? ? <add name="MyContext" connectionString="Data Source=localhost;port=3306;Initial Catalog=aceadmin;user id=root;password=xxx;" providerName="MySql.Data.MySqlClient" />
? </connectionStrings>
3.添加實(shí)體類(lèi)
添加AccountUser類(lèi)
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace EFCodeFirst.Entity
{
? ? [Table("user")]
? ? public class AccountUser
? ? {
? ? ? ? /// <summary>
? ? ? ? /// 用戶(hù)ID
? ? ? ? /// </summary>
? ? ? ? [Column("ID")]
? ? ? ? [Key]
? ? ? ? public int AccountUserId { get; set; }
? ? ? ? /// <summary>
? ? ? ? /// 用戶(hù)名
? ? ? ? /// </summary>
? ? ? ? public string Name { get; set; }
? ? ? ? /// <summary>
? ? ? ? /// 年齡
? ? ? ? /// </summary>
? ? ? ? public Nullable<int> Age { get; set; }
? ? ? ? /// <summary>
? ? ? ? /// 性別
? ? ? ? /// </summary>
? ? ? ? public Nullable<bool> Sex { get; set; }
? ? }
}
注:特性“Table”指定數(shù)據(jù)庫(kù)中與該實(shí)體產(chǎn)生映射的表名,默認(rèn)不添加系統(tǒng)會(huì)去數(shù)據(jù)庫(kù)中尋找表名為:“類(lèi)名+s”的表,找不到會(huì)報(bào)錯(cuò)。
特性“Column”來(lái)指定映射表中的列名,如果屬性名與列名相同,則不用添加,系統(tǒng)默認(rèn)屬性名與列名一致。
以上方式為Data Annotations模式(數(shù)據(jù)注解)映射數(shù)據(jù)庫(kù)方法。
EF還提供Fluent API配置來(lái)映射數(shù)據(jù)庫(kù),下面會(huì)講到。
4.添加Context實(shí)體對(duì)象
using System.Data.Entity;
namespace EFCodeFirst
{
? ? public class DContext : DbContext
? ? {
? ? ? ? /// <summary>
? ? ? ? /// 添加構(gòu)造函數(shù),name為config文件中數(shù)據(jù)庫(kù)連接字符串的name
? ? ? ? /// </summary>
? ? ? ? public DContext() : base("name=MyContext")
? ? ? ? {
? ? ? ? }
? ? ? ? #region 數(shù)據(jù)集
? ? ? ? public DbSet<AccountUser> AccountUsers { get; set; }
? ? ? ? #endregion??
? ? }
}
定義新的上下文類(lèi)DContext集成DbContext
這里聲明了與數(shù)據(jù)庫(kù)映射的對(duì)象AccountUser,以后可以直接用屬性AccountUsers來(lái)進(jìn)行對(duì)數(shù)據(jù)庫(kù)的操作
注:一定要添加構(gòu)造函數(shù)并指明config文件中數(shù)據(jù)庫(kù)連接字符串的name,否則系統(tǒng)將把數(shù)據(jù)庫(kù)默認(rèn)指定到VS自帶的數(shù)據(jù)庫(kù)中
5.測(cè)試簡(jiǎn)單的插入數(shù)據(jù)
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數(shù)據(jù)庫(kù)已經(jīng)成功
6.使用Fluent API配置EF映射關(guān)系
1.添加新類(lèi)省、市
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>
? ? ? ? /// 城市名稱(chēng)
? ? ? ? /// </summary>
? ? ? ? public string CityName { get; set; }
? ? ? ? /// <summary>
? ? ? ? /// 所屬城市
? ? ? ? /// </summary>
? ? ? ? public Provice ProviceData { get; set; }
? ? }
2.添加Fluent API配置類(lèi),繼承自EntityTypeConfiguration對(duì)象
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);? ? ? ? //配置一對(duì)多關(guān)系
? ? ? ? }
? ? }
}
注:由于這里添加了外鍵,則必須用WithRequired方法而不能用WithOption方法,否則報(bào)錯(cuò)
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();
? ? ? ? }
? ? }
}
一對(duì)多關(guān)系只用在一端配置,provice處配置后不需要在city端再配置
3.將Fluent API配置添加到DContext類(lèi)中,重寫(xiě)OnModelCreating方法
public class DContext : DbContext
? ? {
? ? ? ? /// <summary>
? ? ? ? /// 添加構(gòu)造函數(shù),name為config文件中數(shù)據(jù)庫(kù)連接字符串的name
? ? ? ? /// </summary>
? ? ? ? public DContext() : base("name=MyContext")
? ? ? ? {
? ? ? ? }
? ? ? ? #region 數(shù)據(jù)集
? ? ? ? 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方法中級(jí)聯(lián)添加省、市
static void Main(string[] args)
? ? ? ? {
? ? ? ? ? ? try
? ? ? ? ? ? {
? ? ? ? ? ? ? ? var provice = new Provice
? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? ProviceName = "河南省",
? ? ? ? ? ? ? ? ? ? Citys = new List<City>()
? ? ? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? ? ? new City() { CityName = "安陽(yáng)"},
? ? ? ? ? ? ? ? ? ? ? ? new City() { CityName = "鄭州"},
? ? ? ? ? ? ? ? ? ? ? ? new City() { CityName = "洛陽(yáng)"},
? ? ? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? };
? ? ? ? ? ? ? ? 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();
? ? ? ? }
可以看到數(shù)據(jù)庫(kù)中同時(shí)向省表和市表中添加了相關(guān)數(shù)據(jù)
7.EF的Data Annotations與Fluent API是可以同時(shí)使用的,但同效果的配置只需要在二者之一中配置就好。
總結(jié)
以上是生活随笔為你收集整理的Net EF框架+ MySql示例的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: vue中使用cookies和crypto
- 下一篇: WordPress插件 Affiliat