.net學習之Attribute特性和EF關鍵知識點

來源:互聯網
上載者:User

標籤:使用   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類的代理類對象(封裝類對象)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.