首页 > 代码库 > Entity Framework with MySQL 学习笔记一(常用小总结)

Entity Framework with MySQL 学习笔记一(常用小总结)

1-1 设置

   //DataAnnotation 1-1 | 1-0 table     //SQLtable : member , columns : memberId, name    //SQL basic logic : 1个table的PK, 是另一个table的PK and FK , 这就是1-1和1-0的关系    [Table("member")]    public class Member    {        [Key]        public Int32 memberId { get; set; }        public string name { get; set; }        [Required]        /*                    1-0,这里就不要Required            1-1关系最好是放Required啦,在insert的时候才不会出错,但是...             如果你写Required,那么你在做update的时候这个address不能是Null,也就是说一定要inner join出来先,不是很方便.                */        public virtual Address address { get; set; }    }    //SQLtable : address , columns : memberId, postcode, country    [Table("address")]    public class Address    {        /*            关键就是这个关系连接, "member" 是 tableName        */        [Key, ForeignKey("member")]         public Int32 addressId { get; set; } //这里取名addressId也行        public string postcode { get; set; }        public string country { get; set; }        public virtual Member member { get; set; }    }

基本的 CRUD

using (EFDB db = new EFDB()){    /*insert*/    db.members.Add(new Member    {        name = "keatkeat",        address = new Address        {            postcode = "81300",            country = "malaysia"        }    });    db.SaveChanges();    /*select*/    var members = db.members.Include(m => m.address).ToList(); //要include才会一起出来哦              /*update*/    var member = db.members.Include(m => m.address).First().name = "xinyao123";    db.SaveChanges();    /*delete*/    db.members.Remove(db.members.Include(m => m.address).First()); //要include出来才能一次删除2个table的数据!    db.SaveChanges();}
View Code

 1-n 设置

    //1-n     /*        基本上如果没有必要就不要写required了,这样比较方便在update单个table的时候.(insert的时候自己要控制好!)    */    [Table("prod")]    public class Prod    {        [Key]        public Int32 prodId { get; set; }        public string code { get; set; }        public virtual ICollection<Color> colors { get; set; } //有多个colors,用ICollection | List 也可以    }    [Table("color")]    public class Color    {        [Key]        public Int32 colorId { get; set; }        [ForeignKey("prod")] //指定一个FK           public Int32 prodId { get; set; }        public string color { get; set; }        public virtual Prod prod { get; set; } //有一个prod    }

 

Entity Framework with MySQL 学习笔记一(常用小总结)