LINQ to SQL – Các khái niệm cơ bản: Object-Relational Mapping, Entity Class, Association và DataContext (tiếp theo)

Mã nguồn hoàn chỉnh

Lớp Northwnd.cs:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
using System;
using System.Data.Linq;
using System.Data.Linq.Mapping;
namespace Northwnd
{
    [DatabaseAttribute(Name = "northwind")]
    public partial class NorthwindDataContext : DataContext
    {
        public NorthwindDataContext(string connection)
            : base(connection)
        {
        }
        public Table<Category> Categories
        {
            get { return this.GetTable<Category>(); }
        }
        public Table<Product> Products
        {
            get { return this.GetTable<Product>(); }
        }
    }
    [Table(Name = "Categories")]
    public partial class Category
    {
        private int _CategoryID;
        private string _CategoryName;
        private EntitySet<Product> _Products;
        public Category()
        {
            Action<Product> attachProduct = new Action<Product>((p) => p.Category = this);
            Action<Product> detachProduct = new Action<Product>((p) => p.Category = null);
            this._Products = new EntitySet<Product>(attachProduct, detachProduct);
        }
        [Column(Storage = "_CategoryID", AutoSync = AutoSync.OnInsert, DbType = "Int NOT NULL IDENTITY", IsPrimaryKey = true, IsDbGenerated = true)]
        public int CategoryID
        {
            get { return this._CategoryID; }
            set
            {
                if ((this._CategoryID != value))
                    this._CategoryID = value;
            }
        }
        [Column(Storage = "_CategoryName", DbType = "NVarChar(15) NOT NULL", CanBeNull = false)]
        public string CategoryName
        {
            get { return this._CategoryName; }
            set
            {
                if ((this._CategoryName != value))
                    this._CategoryName = value;
            }
        }
        [Association(Name = "FK_Products_Categories", Storage = "_Products", OtherKey = "CategoryID", DeleteRule = "NO ACTION")]
        public EntitySet<Product> Products
        {
            get { return this._Products; }
            set { this._Products.Assign(value); }
        }
    }
    [Table(Name = "Products")]
    public partial class Product
    {
        private int _ProductID;
        private string _ProductName;
        private System.Nullable<int> _CategoryID;
        private EntityRef<Category> _Category;
        public Product()
        {
            this._Category = default(EntityRef<Category>);
        }
        [Column(Storage = "_ProductID", AutoSync = AutoSync.OnInsert, DbType = "Int NOT NULL IDENTITY", IsPrimaryKey = true, IsDbGenerated = true)]
        public int ProductID
        {
            get
            {
                return this._ProductID;
            }
            set
            {
                if ((this._ProductID != value))
                    this._ProductID = value;
            }
        }
        [Column(Storage = "_ProductName", DbType = "NVarChar(40) NOT NULL", CanBeNull = false)]
        public string ProductName
        {
            get { return this._ProductName; }
            set
            {
                if ((this._ProductName != value))
                    this._ProductName = value;
            }
        }
        [Column(Storage = "_CategoryID", DbType = "Int")]
        public System.Nullable<int> CategoryID
        {
            get { return this._CategoryID; }
            set
            {
                if ((this._CategoryID != value))
                {
                    if (this._Category.HasLoadedOrAssignedValue)
                    {
                        throw new ForeignKeyReferenceAlreadyHasValueException();
                    }
                    this._CategoryID = value;
                }
            }
        }
        [Association(Name = "FK_Products_Categories", ThisKey = "CategoryID", IsForeignKey = true)]
        public Category Category
        {
            get { return this._Category.Entity; }
            set
            {
                Category previousValue = this._Category.Entity;
                if (((previousValue != value)
                            || (this._Category.HasLoadedOrAssignedValue == false)))
                {
                    if ((previousValue != null))
                    {
                        this._Category.Entity = null;
                        previousValue.Products.Remove(this);
                    }
                    this._Category.Entity = value;
                    if ((value != null))
                    {
                        value.Products.Add(this);
                        this._CategoryID = value.CategoryID;
                    }
                    else
                    {
                        this._CategoryID = default(Nullable<int>);
                    }
                }
            }
        }
    }
}
Kiểm tra với lớp Program.cs, đoạn mã trong Main() sẽ lấy ra dòng dữ liệu trong bảng Categories có CategoryName bắt đầu bằng “M”, sau đó in ra tất cả các dòng trong bảng Products có liên hệ với Category này:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
using System;
using System.Linq;
using System.Data.Linq;
using Northwnd;
class Program
{
    static void Main()
    {
        NorthwindDataContext db = new NorthwindDataContext("C:\\SampleDB\\Northwnd.mdf");
        Table<Category> categories = db.Categories();
        var query = from c in categories where c.CategoryName.StartsWith("M") select c;
        Console.WriteLine("Category:");
        foreach (var cat in query)
        {
            Console.WriteLine(cat.CategoryID + " | " + cat.CategoryName);
            Console.WriteLine("Products:\n\t{0,-4} | {1,-25} | {2}\n","ID","Name","CategoryID");
            foreach (var p in cat.Products)
                Console.WriteLine("\t{0,-4} | {1,-25} | {2}",p.ProductID,p.ProductName,p.CategoryID);
        }
        Console.Read();
    }
}
Output:
Category:
6 | Meat/Poultry
Products:
        ID   | Name                      | CategoryID

        9    | Mishi Kobe Niku           | 6
        17   | Alice Mutton              | 6
        29   | Thüringer Rostbratwurst   | 6
        53   | Perth Pasties             | 6
        54   | Tourtière                 | 6
        55   | Pâté chinois              | 6

Kết luận

Trong khuôn khổ của bài viết tôi chỉ trình bày về cách tạo các entity class với các DatabaseAttribute, ColumnAttribute và AssociationAttribute. Mã nguồn của các entity class trên được tạo ra bằng công cụ SQLMetal và được tôi rút gọn để tiện trình bày.

Nhận xét

Bài đăng phổ biến từ blog này

Khôi phục phân vùng ổ cứng do ghost nhầm theo Hieuit.net

Cách sử dụng 2 phương thức [httppost] và [httpget] trong MVC theo https://dzungdt.wordpress.com

MVC định dạng tiền tệ vnđ - Format currency vnd in MVC