Net EF框架+ MySql示例
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是可以同時使用的,但同效果的配置只需要在二者之一中配置就好。
總結
以上是生活随笔為你收集整理的Net EF框架+ MySql示例的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: vue中使用cookies和crypto
- 下一篇: WordPress插件 Affiliat