Code First 可以自動根據Model 映射來創建數據庫,這點非常方便。 但是按照上一節的方式創建的表,會發現,所有字符串列都是nvarchar(max),就是說每個model的屬性映射的表列都是采用CodeFist 默認的設置進行創建。 這當然不科學,CodeFirst 提供了數據注釋(Data Annotation) 的方式來標記每個模型的屬性與表之間的映射。
成都創新互聯長期為數千家客戶提供的網站建設服務,團隊從業經驗10年,關注不同地域、不同群體,并針對不同對象提供差異化的產品和服務;打造開放共贏平臺,與合作伙伴共同營造健康的互聯網生態環境。為友好企業提供專業的做網站、網站制作,友好網站改版等技術服務。擁有十多年豐富建站經驗和眾多成功案例,為您定制開發。Convention for key | [Key] | 標記為主鍵,默認是把類名+ID 的屬性標記為主鍵 |
Convention for string properties | [maxLength(N)] [minLength(N)] [Required] | 字符大長度,映射到數據庫 字符最小長度,CodeFirst 中檢查,不映射到數據庫 必填 (字符串都映射為nvarchar(n),默認設置長度映射為n=max) |
Convention for Byte Array | Column(TypeName="Image") | 把字節型數據映射為Image 類型,默認映射為varbinary(max) |
Convention for Booleans | sqlserver映射為bit 類型 | |
Convention for One-to-Many ReleationShips | 外鍵關系,映射為 表名_主鍵列 |
1 修改Custom 的模型代碼: 添加using System.ComponentModel.DataAnnotations; 引用
using System.ComponentModel.DataAnnotations;
using System.Collections.Generic;
namespace QuickStart.Model
{
// [Table("Customer")]//存儲表名Customer,默認是類名
public class Customer
{
public Customer() {
this.Orders = new List<Order>();
}
[MaxLength(50)]
public string CustomerID { get; set; }
[Required] //必填
[MaxLength(50)] //大長度50個漢字
public string Name { get; set; }
public decimal Balance { get; set; }
/// <summary>
/// 客戶與訂單是one or many
/// </summary>
public List<Order> Orders { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace QuickStart.Model
{
public class Order
{
public Order() {
this.CreateTime = DateTime.Now;
this.OrderItems = new List<OrderItem>();
}
public int OrderID { get; set; }
[MaxLength(50)]
public string Title { get; set; }
public decimal Total { get; set; }
public DateTime CreateTime { get; set; }
//one or many
public List<OrderItem> OrderItems { get; set; }
// one or one
public Customer Customer { get; set; }
}
}
當模型被修改后,此時如果直接運行代碼,Code First 會拋出一個異常,說 要創建的OrderBD 已經存在。 默認配置下CodeFisrt 是不會自動修改的。
所以,需要添加一個初始化配置,在main函數代碼開始的時候,讓Code First 去檢測Model 是否發生更改,如果更改,就刪掉原數據庫,然后重新創建一個新的數據庫。 此種方式更新數據庫,必須要保證數據庫在其他地方為被使用,否則刪除數據庫時將不會成功。
1 確保配置文件中,鏈接字符串包含保存密碼配置 Persist Security Info=true
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="OrderDB" providerName="System.Data.SqlClient"
connectionString="server=.;uid=sa;pwd=123456;database=OrderDB;Persist Security Info=true"/>
<!--要CodeFirst能自動維護model的更改,必須添加Persist Security Info=true 項,表示保持賬號密碼-->
</connectionStrings>
</configuration>
2 在main 函數中添加 using System.Data.Entity; 引用。 (此處代碼與第一小節有點變化,更改過了,不過應該可以看懂)。粗體代碼為修改部分
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using QuickStart.Model;
using System.Data.Entity;
namespace QuickStart
{
class Program
{
static void Main(string[] args)
{
//數據庫變動初始化方法一:每次檢查數據庫上下文,如果模型Model發生變化,就刪除現有數據庫,重新創建
Database.SetInitializer(new DropCreateDatabaseIfModelChanges<DBContextAPI>());
CreateCustomer(); //創建顧客
Console.ReadKey();
}
private static void CreateCustomer()
{
using (var db = new DBContextAPI())
{
var customer = new Customer()
{
CustomerID = "20121224001",
Name = "張三",
Balance = 1000
};
db.Customers.Add(customer);
int result = db.SaveChanges();
Console.WriteLine("追加{0}條記錄成功!", result);
}
}
}
}
3 執行,成功后,表結構發生變化。
網頁名稱:ADO.NETEntityFramework-CodeFisrt(二)-創新互聯
本文鏈接:http://vcdvsql.cn/article20/cedhco.html
成都網站建設公司_創新互聯,為您提供網站設計公司、用戶體驗、網頁設計公司、網站改版、品牌網站設計、外貿網站建設
聲明:本網站發布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網站立場,如需處理請聯系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經允許不得轉載,或轉載時需注明來源: 創新互聯