zoukankan      html  css  js  c++  java
  • Domain Model & Code First

    领域模型(Domain Medel)是从现实世界业务逻辑抽象为业务实体,所以这种模式用Code First更适合。利用上章案例接受下Entity FrameworkCode first的强大功能。

    安装EF

    通过Package Manager Console安装EF: install-package entityframework默认会安装最新版本

    Model创建类

    注意关键字virtual,为实体关联到的属性,代码下载

       public class BankAccount
        {
            public Guid BankAccountId { get; set; }
            public decimal Balance { get; set; }
            public string CustomerRef { get; set; }
            public virtual ICollection<Transaction> Transactions { get; set; }
        }
    
            public class Transaction
        {
            public int ID { get; set; }
            /// <summary>
            /// 保存到表中为BankAccount的外键
            /// </summary>
            public Guid BankAccountId { get; set; }
            public decimal Deposit { get; set; }
            public decimal Withdraw { get; set; }
            public string Reference { get; set; }
            public DateTime Date { get; set; }
            public virtual BankAccount BankAccount { get; set; }
        }
    

    连接数据库指定及Context创建

    webconfig文件中添加

      <connectionStrings>
         <add name="BankAccountContext" connectionString="Data Source=(LocalDb)mssqllocaldb;AttachDbFilename=|DataDirectory|BankAccount.mdf;Initial Catalog=BankAccount;Integrated Security=SSPI;" providerName="System.Data.SqlClient" />
      </connectionStrings>
    

    添加数据上下文

       public class BankAccountContext: DbContext
        {
            public DbSet<BankAccount> BankAccounts { get; set; }
        }
    

    利用Package Manager console完成数据库初始化

    1. enable-migrations 会添加类Configuration,添加测试数据在 Seed方法中添加
     var bankAccounts = new List<BankAccount>
        {
            new BankAccount { BankAccountId=new Guid("27B5318E-EEA5-404C-ABE4-185C3411917E"), Balance=73.00m,CustomerRef="Bob Account" },
            new BankAccount { BankAccountId=new Guid("C2F81C0C-2EFD-40EF-BBC6-B394CF80EDF0"), Balance=456.00m,CustomerRef="Scott Test" },
            new BankAccount { BankAccountId=new Guid("903BB2F8-019A-47D6-88E4-DFD2AC9BB323"), Balance=0.00m,CustomerRef="Marys Account" }
        };
    
    1. 添加本次对数据库的修改add-migration InitialCreate,以后每次每次为Model中类添加属性(对应表添加字段)都需要执行add-migration 生成的文件名再同步到数据库
    2. 同步到数据库update-database,可用看到App_Data文件夹下添加了一个BankAccount.mdf文件

  • 相关阅读:
    SSH免密码登录
    Qt编译错误GL/gl.h: No such file or directory
    UVA 11645
    《逆袭大学》文摘——9.4 基础和应用的平衡中找到大学的节奏
    EBS採购模块中的高速接收和高速接收事务
    笔记-Android中打开各种格式的文件(apk、word、excel、ppt、pdf、音视频、图片等)
    git 冲突解决的方法
    SICP 习题 (1.43)解题总结
    Swift百万线程攻破单例(Singleton)模式
    setjmp/longjmp
  • 原文地址:https://www.cnblogs.com/LoveTomato/p/9397569.html
Copyright © 2011-2022 走看看