標籤:使用 strong 檔案 資料 new 資料庫 sql .net
一、Attribute特性/標籤
1.Attribute用來對類、屬性、方法等標註額外的資訊,貼一個標籤
簡單的說,定製特性Attribute,本質上就是一個類,它為目標元素提供關聯附加資訊,並在運行時以反射的方式來擷取附加資訊。
[Obsolete("此方法已淘汰")]
public void SayHi()
{
}
加上Obsolete特性,當滑鼠放到調用方法上的時候,就會提示此方法已淘汰
2.Attribute自訂屬性類別
Attribute就是類,Attribute類名一般都以Attribute結尾
不帶資料的屬性類別
//定義 屬性類別
public class FlyAttribute : Attribute
{
}
//使用 自訂特性
[Fly] //或者 [FlyAttribute] 可省略 Attribute
puclic class Dog
{
}
帶資料的屬性類別
//定義 屬性類別
public class FlyAttribute : Attribute
{
public string Name{get;set;}
public FlyAttribute(string strName)
{
this.Name = strName;
}
}
//使用 自訂特性
[Fly("小白")] //或者 [FlyAttribute] 可省略 Attribute
puclic class Dog
{
}
3.擷取特性裡的資料
通過反射擷取
Dog d = new Dog();
Type dogType = d.GetType();
object [] attrs = t.GetCustomAttributes(typeof(FlyAttribute), false);
FlyAttribute dogAttr = attrs[0] as FlyAttribute;
string strName = dogAttr.Name;
二、EF
1.NHibernate不需要寫sql語句;ibaties需要寫sql語句,是半開放的持久層架構。
2.edmx檔案解析
edmx定義三大部分,SSDL content(定義資料庫部分)、CSDL content(定義C#類)、C-S mapping content(定義資料庫和C#類之間的關係)
3.EF刪除、修改
User u = new User(){id=1};
db.Users.Attach(u);
db.Users.Remove();
db.SaveChanges();
User u = new User(){id=1,UserName="aa"};
DbEntityEntry<User> entry = db.Entry<User>(u);
entry.State = EntityState.Unchanged;
entry.Property("UserName").IsModified = true;
db.SaveChanges();
4.消極式載入
IQueryable<UserAddress> addrs = db.UsersAddresses.Where(x=>x.userId = 1);//真實返回的是DbQuery對象,以介面的形式接收
當外鍵實體相同的時候,只會查詢一次出來,不會重新查詢
5.表內串連
IQueryable<UserAddress> addrs = db.UsersAddresses.Include("Users");
6.代理類對象
User user = db.Users.Where(u=>u.id=1).FirstOrDefault();//注意,此時返回的是一個User類的代理類對象(封裝類對象)