标签:测试数据 dir cat security tab text tco epo 版本
领域模型(Domain Medel)是从现实世界业务逻辑抽象为业务实体,所以这种模式用Code First更适合。利用上章案例接受下Entity Framework
的Code first
的强大功能。
通过Package Manager Console安装EF:install-package entityframework
默认会安装最新版本
注意关键字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; }
}
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
完成数据库初始化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" }
};
add-migration InitialCreate
,以后每次每次为Model中类添加属性(对应表添加字段)都需要执行add-migration 生成的文件名
再同步到数据库同步到数据库update-database
,可用看到App_Data
文件夹下添加了一个BankAccount.mdf
文件
标签:测试数据 dir cat security tab text tco epo 版本
原文地址:https://www.cnblogs.com/LoveTomato/p/9397569.html