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 Users { get; set; } 
        public DbSet 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 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的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();
            }
        }
    }


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

原码例子

你可能感兴趣的:(C#,Entity,Framework)