EntityFramework-MySql
通过MySql 来实现EF 功能 步骤:
1.建立项目,安装MySql,EntityFramework 相关包
install-package EntityFramework
install-package MySql.Data.Entity
2.建立实体对应的数据库表
引用单元:using System.ComponentModel.DataAnnotations.Schema; //该单元定义了一些属性,用于标注映射关系
[Table("t_person")] //该类映射的数据库中对应的表为 t_person
public class Person{
[Column(id)] //该字段映射表中的字段为id
public int Id{get;set;}
[Column("name")]
public string Name{get;set;}
}
[Table("t_article")]
public class Article{
[Column("id")]
public int Id{get;set;}
[Colunm("person_id")]
public int PersonId{get;set;}
[Column("name")]
public string Name{get;set;}
[Column("description")]
public string Description{get;set;}
}
3.建立表:
mysql -uroot -p
>use test
drop table if exists t_article
create table t_article(id int auto_increment primary key,person_id int not null,name varchar(30),description text)engine=innodb,default charset=utf8;
drop table if exists t_person(int id auto_increment primary key,name varchar(30))engine=innodb,charset=utf8;
4.修改配置文件,增加链接字符串
<connectionStrings>
<add name="mysqldb" connectionString="server=localhost;port=3306;database=test;user=root;password=123;Character Set=utf8;" providerName="MySql.Data.MySqlClient"/>
</connectionStrings>
5.建立实体类
引用单元:using system.data.Entity;
[DbConfigurationType(typeof(MySql.Data.Entity.MySqlEFConfiguration))] //这个应该和java 的 Java.Classfor(xxx) 有点类似,指定数据库类型
public class DemoContext:DbContext{
static DemoContext(){
Database.SetInitializer<DemoContext>(null); //实例化是根据指定的数据库类型进行实例化 code-first
}
public DemoContext():base("name=mysqldb"){}
public DbSet<Person> Persons{get;set;}
public DbSet<Article> Articles{get;set;}
}
完整示例:
using System.Data.Entity;
namespace ConsoleMySqlEF.Models
{
[DbConfigurationType(typeof(MySql.Data.Entity.MySqlEFConfiguration))]
public class DemoContext:DbContext
{
static DemoContext()
{
Database.SetInitializer<DemoContext>(null);
}
public DemoContext() : base("name=mysqldb") { }
public DbSet<Person> Persons { get; set; }
public DbSet<Article> Articles { get; set; }
}
}
调用示例:
using ConsoleMySqlEF.Models;
namespace ConsoleMySqlEF
{
class Program
{
static void Main(string[] args)
{
using (var db = new DemoContext())
{
using (var tran=db.Database.BeginTransaction())
{
try
{
Person person = new Person() { Name = "demo" };
db.Persons.Add(person);
db.SaveChanges();
Article article = new Article()
{
PersonId = person.Id,
Description = "Delphi",
Name = "Test"
};
db.Articles.Add(article);
db.SaveChanges();
tran.Commit();
Console.WriteLine("添加数据成功!");
}
catch(Exception ex) {
tran.Rollback();
throw;
}
}
Console.ReadLine();
}
}
}
}