EF Code First 入门 包括 数据迁移 导航属性 为null 的情况

App.config

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
  </startup>
  <entityFramework>
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>
  <connectionStrings>
    <add name="ZQDB" connectionString="server=10.132.0.34;database=ZQDBTest; uid=sa;pwd=SAsa12" providerName="System.Data.SqlClient" />
  </connectionStrings>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Runtime.CompilerServices.Unsafe" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-4.0.6.0" newVersion="4.0.6.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Memory" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-4.0.1.1" newVersion="4.0.1.1" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Extensions.Primitives" publicKeyToken="adb9793829ddae60" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-3.1.2.0" newVersion="3.1.2.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Extensions.Configuration.Abstractions" publicKeyToken="adb9793829ddae60" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-3.1.2.0" newVersion="3.1.2.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Extensions.DependencyInjection.Abstractions" publicKeyToken="adb9793829ddae60" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-3.1.2.0" newVersion="3.1.2.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Extensions.Caching.Abstractions" publicKeyToken="adb9793829ddae60" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-3.1.2.0" newVersion="3.1.2.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Extensions.Options" publicKeyToken="adb9793829ddae60" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-3.1.2.0" newVersion="3.1.2.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Extensions.Logging.Abstractions" publicKeyToken="adb9793829ddae60" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-3.1.2.0" newVersion="3.1.2.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Extensions.DependencyInjection" publicKeyToken="adb9793829ddae60" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-3.1.2.0" newVersion="3.1.2.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.ComponentModel.Annotations" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-4.2.1.0" newVersion="4.2.1.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
</configuration>

创建三个类,第三个类 是 EF的上下文

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

namespace EF_CODEFIRST_Test
{
    class GreadInfo
    {
        [Key]
        public int id { get; set; }
        [StringLength(32)] //长度
        [Required]
        public string number { get; set; }
        [Required]
        public DateTime createTime { get; set; }

        public virtual ICollection<Student> Student {get;set;}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations;

namespace EF_CODEFIRST_Test
{
    class Student
    {
        [Key]
        public int id { get; set; }    //默认主键自增
        [Required]
        public string number { get; set; }
        [Required]
        public string name { get; set; }
        [Required]
        public int age { get; set; }
        [Required]
        public DateTime birthday { get; set; }

        public virtual GreadInfo GreadInfo { get;set;}
    }
}
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EF_CODEFIRST_Test
{
    class CodeFirstDBContext:DbContext
    {
        public CodeFirstDBContext():base("name=ZQDBTestEntities")
        {

        }

        //模型映射成表的时候这个方法被执行
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();  //将映射成的表移除复数约定,不加s
        }

        //定义俩个属性表示可以对实体进行操作
        public DbSet<GreadInfo> GreadInfo { get; set; }
        public DbSet<Student> Student { get; set; }

    }
}

添加应用程序配置文件 App.config

添加 链接字符串,与上下文中对应的一样

<connectionStrings>
    <add name="ZQDBTestEntities" connectionString="Data Source=10.132.0.34;Database=ZQDBTest;UID=sa;PWD=SAsa12;" providerName="System.Data.SqlClient"></add>
  </connectionStrings>

 

安装 包  EntityFramework  添加引用  entity

 

 

在p'rogram.cs 中使用

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

namespace EF_CODEFIRST_Test
{
    class Program
    {
        static void Main(string[] args)
        {
            CodeFirstDBContext dbContext = new CodeFirstDBContext();
            dbContext.Database.CreateIfNotExists();// 没有就创建DB
            Student s = new Student();
            s.id = 1;
            //s.name = "张三";
            //s.number = "3452";
            //s.age = 15;
            //s.birthday = DateTime.Now.AddYears(-15);
            GreadInfo g = new GreadInfo();
            g.id = 1;
            g.number = "01";
            g.createTime= DateTime.Now.AddYears(-30);
            dbContext.GreadInfo.Add(g);
            var i=dbContext.SaveChanges();
            Console.WriteLine(i);
            Console.ReadKey();

        //当对象中有外键的时候,且保存对象的时候同时也要保存外键
        如果外键不存在,那么新建外键对象,然后赋给 对象的 外键属性,保存的时候,先保存外键对象,再保存 对象。如果id是自增的话,那么ID可以不设。
        如果外键存在,那么 需要从DB中查询出这个对象上下文,然后赋给对象,再保存


        //查询数据的时候,我们可以通过对象,来查询出对象的外键
        var gg = dbContext.GreadInfo.Include("Student").Where(g => g.id == 1).FirstOrDefault();  //不用 include包含 导航属性的话,会查不到导航属性,不知道原因
                 foreach(var s in gg.Student)
                {
                    Console.WriteLine(s);
                }
        //但是我查询的时候,外键一直都是null,不知道原因。然后百度了一下,有一个折中的办法就是
        在DB查询的时候 include  外键对象,这个叫贪懒加载,查询的时候就直接加载起来
        }
    }
}

 

导航属性

数据迁移

记住,数据迁移的时候一定要选对控制台上面的默认项目

注意,数据迁移不会删除原表的数据,只是新增一个栏位

ALTER TABLE [dbo].[GreadInfo] ADD [master] [nvarchar](max)
INSERT [dbo].[__MigrationHistory]([MigrationId], [ContextKey], [Model], [ProductVersion])
VALUES (N'202003250404597_AutomaticMigration', N'EF_CODEFIRST_Test.Migrations.Configuration',  

第一步:打开NuGet控制台,输入"Enable-Migrations"启用Code First迁移。.

第二步:在控制台中输入“Add-Migration AddUrl”,其中AddUrl是迁移的名称,方便以后根据这个名称进行降级。

第三步:在控制台中输入“Update-Database” 或者 Update-Database -Verbose ,这个时候可能会因为当前项目不是启动项而报错,我们可以执行Update-Database的时候指定启动,这么我只是简单的将当前项目设置为启动项。

 

 

有的时候第一步会报错,我遇到一个错误

未能加载文件或程序集“EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089”

原因是我安装了多个 entityFramework的包,卸载就好了

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值