ef03

 

1、codeFirst

注意codefirst不同于modelfirst,之前的表述是错误的。

codefirst是几步先建模型,也不先建表。

通过代码进行映射

进行EF模型的映射及使用EF提供的数据库操作类需要借助两个引用:

System.Data.Entity:直接右键引用搜索添加

EntityFrame:NutGet包管理工具内搜索下载,注意版本

下面展示构建流程:

 

1)新建项目

2)根据需求建立所需要的数据的类,并注意添加关联:

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CFDemo01
{
    class ClassInfo
    {
        [Key]
        public int Id { get; set; }
        [StringLength(32)]
        [Required]
        public string ClassName { get; set; }
        [Required]
        public DateTime CreateTime { get; set; }

        // 外键,与学生实体相关联,1对多关系
        public virtual ICollection<Student> Student { get; set; }
    }
}
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CFDemo01
{
    class Student
    {
        [Key]
        public int Id { get; set; }
        [StringLength(32)]
        [Required]
        public string StuName { get; set; }
        [Required]
        public DateTime EnterDate { get; set; }


        // 外键,与学生实体相关联,多对1关系
        public virtual ClassInfo ClassInfo { get; set; }
    }
}

注意限定属性

3)根据开头安装相关引用

4)添加ef的数据库操作类

首先在配置文件(App.config)中进行连接字符串额配置:

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <configuration>
 3   <configSections>
 4     <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
 5     <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
 6   </configSections>
 7   <startup>
 8     <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />
 9   </startup>
10   <entityFramework>
11     <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
12   </entityFramework>
13   <connectionStrings>
14     <add name="connStr" connectionString="server=127.0.0.1;uid=sa;pwd=123456;database=EFDemo" providerName="System.Data.Sqlclient"/>
15   </connectionStrings>
16 </configuration>

然后编写这一个类:

using System;
using System.Collections.Generic;
using System.Data.Entity.ModelConfiguration.Conventions;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CFDemo01
{
    class CodeFirstDbContext:DbContext
    {
        // 构造方法
        public CodeFirstDbContext() : base("name=connStr")
        {
        }

        // 记住就好,模型映射成表时执行,移除复数指令
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
        }

        public DbSet<ClassInfo> ClassInfo { get; set; }
        public DbSet<Student> Student { get; set; }

    }
}

5) 在入口方法中实践

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CFDemo01
{
    class Program
    {
        static void Main(string[] args)
        {
            CodeFirstDbContext db = new CodeFirstDbContext();
            // 如果数据库不存在,进行创建
            db.Database.CreateIfNotExists();
            ClassInfo classInfo = new ClassInfo();
            Student stu = new Student();
            classInfo.ClassName = "1班";
            classInfo.CreateTime = DateTime.Now;
            stu.StuName = "Noah";
            stu.EnterDate = DateTime.Now;
            db.ClassInfo.Add(classInfo);
            db.Student.Add(stu);
            db.SaveChanges();
            Console.WriteLine("完成");
            Console.ReadLine();
        }
    }
}

执行后,系统会为我们创建相应的表,并添加指定的数据

 

小贴士:注意如果使用linq语句查询只需要查询某几个字段,可以:

 

 

2、使用Lambda表达式进行查询:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CFDemo01
{
    class Program
    {
        static void Main(string[] args)
        {
            CodeFirstDbContext db = new CodeFirstDbContext();
            var classList = db.ClassInfo.Where<ClassInfo>(u => u.Id == 1);
            foreach(var classInfo in classList)
            {
                Console.WriteLine(classInfo.ClassName);
            }
            Console.ReadLine();
        }
    }
}
// 进行排序
var
classList = db.ClassInfo.Where<ClassInfo>(u => true).OrderBy<ClassInfo,int>(u=>u.Id);

linq的写法:(降序

分页

 

linq分页

 

 

 

posted on 2020-03-08 21:59  Tanqurey  阅读(219)  评论(0编辑  收藏  举报