MySql For Entity Framework 6 Code First 例子

编译环境为:

Visual Studio 2010 + MySql 5.6 + Connector 6.8.3 + Entity Framework 6


Demo过程:

1. 建立Console 项目:EntityFramework.CodeFirst.Demo

2. 添加Entity Framework引用,我是通过NuGet添加的

3. 添加MySql.Data.Entity.EF6引用,添加方法同上

4. 添加类:TestEntities.cs,代码:

    [DbConfigurationType(typeof(MySqlEFConfiguration))]
    class TestEntities : DbContext
    {
        public DbSet<User> Users { get; set; } 
        public DbSet<Department> Departments { get; set; } 
    }

    public class Department
    {
        [Key]
        public Guid Id { get; set; }
        [Required]
        [MaxLength(20, ErrorMessage = "Department name must be 20 characters or less"), MinLength(5)]
        [ConcurrencyCheck]
        public string Name { get; set; }

        public virtual ICollection<User> Users { get; set; } 
    }

    public class User
    {
        [Key]
        public Guid Id { get; set; }
        [Required]
        public string Name { get; set; }
        public DateTime Birthday { get; set; }
        public char Gender { get; set; }
        public string Email { get; set; }
        public bool Deleted { get; set; }

        public Guid DepartmentId { get; set; }

        [ForeignKey("DepartmentId")]
        public virtual Department Department { get; set; }
    }


4. App.config 添加配置节:

<!-- connectionStrings -->
<add name="TestEntities" connectionString="Data Source=192.168.103.193; port=3306; Initial Catalog=Test; uid=root; pwd=grasp;" providerName="MySql.Data.MySqlClient" />

<!-- providers -->
<provider invariantName="MySql.Data.MySqlClient" type="MySql.Data.MySqlClient.MySqlProviderServices, MySql.Data.Entity.EF6" />

注意connectionStrings的name必须和实体类名一致


5. 验证:

class Program
    {
        static void Main(string[] args)
        {
            DbConfiguration.SetConfiguration(new MySqlEFConfiguration());
            using (TestEntities db = new TestEntities())
            {
                var dep = new Department {Id = Guid.NewGuid(), Name = "测试部"};
                db.Departments.Add(dep);
                db.SaveChanges();
            }
        }
    }


如果没有意外应该可以成功!

原码例子

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值