1.实体类:
[Table(Name="Customers")]
public class Customer
{
public string CustomerID;
public string City;
}
使用Attribute定义ORM的关系,这样的好处是无需产生和维护大量映射文件。
[Table(Name="Customers")]
public class Customer
{
[Column(Id=true)]
public string CustomerID;
[Column]
public string City;
}
通过Attribute自定义列,定义主键(PK)……
2.数据上下文
// DataContext takes a connection string
DataContext db = new DataContext("c:\\northwind\\northwnd.mdf");
// Get a typed table to run queries
Table<Customer> Customers = db.GetTable<Customer>();
// Query for customers from London
var q =
from c in Customers
where c.City == "London"
select c;
foreach (var cust in q)
Console.WriteLine("id = {0}, City = {1}", cust.CustomerID, cust.City);
这个比较猛,直接写查询,from in where select都成了关键字。直接在对象上进行查询不再考虑数据库了。并且范型化了。
看到var,众位做过asp的兄弟是不是很亲切阿,这是动态语言(解释语言)的特性,变量定义时不定义类型,不过这里应该不是动态语言,应该是根据上下文在编译时确定类型的。
Northwind db = new Northwind("c:\\northwind\\northwnd.mdf");
var q =
from c in db.Customers
where c.City == "London"
select c;
foreach (var cust in q)
Console.WriteLine("id = {0}, City = {1}",cust.CustomerID, cust.City);
简单写法。
public partial class Northwind : DataContext
{
public Table<Customer> Customers;
public Table<Order> Orders;
public Northwind(string connection): base(connection) {}
}
继承一下,表成了成员了。
3.关系定义
[Table(Name="Customers")]
public class Customer
{
[Column(Id=true)]
public string CustomerID;
...
private EntitySet<Order> _Orders;
[Association(Storage="_Orders", OtherKey="CustomerID")]
public EntitySet<Order> Orders {
get { return this._Orders; }
set { this._Orders.Assign(value); }
}
}
[Table(Name="Orders")]
public class Order
{
[Column(Id=true)]
public int OrderID;
[Column]
public string CustomerID;
private EntityRef<Customer> _Customer;
[Association(Storage="_Customer", ThisKey="CustomerID")]
public Customer Customer {
get { return this._Customer.Entity; }
set { this._Customer.Entity = value; }
}
}
Customer和Order是一对多关系,Customer中EntitySet是实体集合,
即此Customer对应的orders,而Association来定义关系(在Property定义),OtherKey表示Order中的CustomerID是此关系的Key。而Order中EntityRef表示这是一个实体引用,用于返回Customer实体,他也是为了支持延时加载(Lazy)用的。Storage是为了表示该Property所对应的成员。