• Entity Framework5 code first 学习1


           因为要学习Nopcommerce,就学习了EF5 CodeFirst。当初在Nopcommerce 1.9中是EF4,说实话对Linq to Entity 不大喜欢。如今却发现这个新技术有大行其道的趋势了。

    拥抱变化吧。

          Code First其宗旨大概是不用先建立数据库,不用EF4里的edmx配置文件,通过编码就可以建立数据库,操纵数据库。传统的开发方法一般都要先建数据库。

          使用Code First,有两个有用的类:DBContext,DBSet。所属命名空间:System.Data.Entity。当然要引入一个EntityFramework.dll。

          必须先建立一个DBContext的子类,去连接建立数据库。

          DBSet 是一个实体的集合。

         假如有这么个案例宠物医院收治患畜的业务模型。

     1 public   class Patient
     2 {
     3 
     4         public Patient()
     5         {
     6 
     7             Visits = new List<Visit>();
     8 
     9         }
    10         public int Id { get; set; }
    11 
    12         public string Name { get; set; }
    13        
    14         public DateTime BirthDate { get; set; }
    15         public AnimalType AnimalType { get; set; }
    16         public DateTime FirstVisit { get; set; }
    17         public List<Visit> Visits { get; set; }
    18
    19     }

        定义这样一个实体,将要映射到数据库中,成为一个表。看看这个定义,有经验的人会问到:

    主键是哪个字段?Name这个字段长度是多少?你猜对了,这个定义还少了一些东西,用于对实体进行限定。

    限定实体有两种方式: DataAnnotations 和 Fluent API。前者简单,后者有点繁琐,但是后者可以做一些前者做不到的事情。

    实体在使用DataAnnotations定义数据库和验证,要引入这两个namespace:

    using System.ComponentModel.DataAnnotations;
    using System.ComponentModel.DataAnnotations.Schema;

    主要的DataAnnotationAttribute有这么几个:

    [Key]

    数据库: 定义主键

    [Required]

    数据库: 会把字段设置成not null

    验证: 会要求必须输入

    是否可以为null [Required(AllowEmptyStrings = false)] 不能为null和空字符串

    [MaxLength] [MinLength]

    [ForeignKey("列名")]

    这个是定义外键的。

    定义好实体之后,DBContext和dbset出场。

        public class VetContext : DbContext
        {
            public VetContext(string contstr):base(contstr)
            {
            }
            public DbSet<Patient> Patients { get; set; }
            public DbSet<Visit> Visits { get; set; }
    
        }
    

      注意VetContext的构造函数,参数是数据库连接串,好像SqlConnection哦,

      private static void CreateNewPatient()
            {
                var dog = new AnimalType { TypeName = "Dog" };
                var patient = new Patient
    
                {
    
                    Name = "Sampson",
                    BirthDate = new DateTime(2008, 1, 28),
                    FirstVisit = new DateTime(2011,1,1),
                    AnimalType = dog,
                    Visits = new List<Visit>{
    new Visit{Date = new DateTime(2011, 9, 1)}
    }
    
                };
    
                using (var context = new VetContext("Data Source=localhost;Initial Catalog=EFTest;Integrated Security=False;Persist Security Info=False;User ID=sa;Password=aa;MultipleActiveResultSets=True"))
                {
    
                    context.Patients.Add(patient);//将实体添加到集合中
                    context.SaveChanges();//修改数据库
    
                }
    
            }
            static void Main(string[] args)
            {
                CreateNewPatient();
            }
    

      

    例子附件

  • 相关阅读:
    首次搭建微信小程序记录各种细节
    vue3.x 首次搭建
    通过nodejs 下载阿里云省、市、区的json文件,使用在echart上
    vscode
    使用 ts + and design + react-redux + react-router-dom + ahook 开发 管理后台
    Python 字典(dict) 操作基础
    高斯混合模型视频背景建模的EM算法与Matlab 实现
    Tensorflow 10分钟快速上手
    Ubuntu16.04LTS 搜狗输入法无法输入中文
    Machine Learning Class 1:Introduction,supervised & unsupervised learning
  • 原文地址:https://www.cnblogs.com/xinchuang/p/3120439.html
Copyright © 2020-2023  润新知