Cấp bậc tác giả:

TRAINING

[TUT .netTiers]Giới thiệu Lớp Entity

Được viết bởi webmaster ngày 14/05/2013 lúc 11:39 PM
Bài trước Tôi đã giới thiệu về Database và SQL trong việc "sinh" code tự động như thế nào. Bài này Tôi sẽ giới thiệu về lớp Entity, một trong những lớp quan trọng không thể thiếu trong Template .netTiers.
  • 0
  • 10358

[TUT .netTiers]Giới thiệu Lớp Entity

Bài trước Tôi đã giới thiệu về Database và SQL trong việc "sinh" code tự động như thế nào. Bài này Tôi sẽ giới thiệu về lớp Entity, một trong những lớp quan trọng không thể thiếu trong Template .netTiers.

Entity là gì?

Entity(thực thể) không phải là kiểu .net, nó là kiểu quan trọng chứa một ý nghĩa nội tại cần thiết trong ứng dụng của bạn. Khái niệm Entity trong ứng dụng business. .NetTiers là phù hợp, nắm giữ ý nghĩa đặc biệt cho dữ liệu. Ví dụ: Employee, Order, OrderDetail là những entity. Các kiểu của chúng đảm bảo tính toàn vẹn của thực thể.

Bạn có thể nghĩ về Entity như phản chiếu của cơ sở dữ liệu, bảng tiếp xúc trong hướng đối tượng. Từ Entity là giống nhau thường được sử dụng, hầu hết là cơ sở dữ liệu-Bảng. Vì vậy, trong môi trường .Net đối tượng tham chiếu cơ sở dữ liệu, Cột của nó trông như lớp Properties(thuộc tính), cẩn thận phù hợp với các kiểu dữ liệu giữa các cơ sở dữ liệu cột và kiểu .Net(ví dụ chuỗi varchar và Int16 cho smallint) .

Bây giờ nghĩ về cơ sở dữ liệu-Bảng "NGƯỜI SỬ DỤNG" ở đâu, chắc chắn, mỗi hàng của bảng là đại diện cho thông tin đầy đủ người dùng duy nhất (như ID của mình, tên, tuổi và địa chỉ). Tưởng tượng đối tượng 'Người dùng'(với thuộc tính ID, tên, tuổi và địa chỉ). Nó đại diện cho người dùng từ cơ sở dữ liệu bảng 'Người dùng' hoặc một hàng của cơ sở dữ liệu bảng.

Kiến trúc. netTiers cho chúng ta môi trường mà chúng ta có thể kiểm soát các entity cơ sở dữ liệu (bảng) bằng cách truyền qua chúng trong phương thức đặc biệt. Trong thực tế, những phương thức đặc biệt kiểm soát các entity .NET gọi là "Controller Objects". Chúng ta sẽ nghiên cứu về chúng trong bài viết tiếp theo. Bây giờ chúng ta phải chắc chắn rằng chúng ta có thể gọi một số phương thức chuyên dụng từ các đối tượng điều khiển để lấy thực thể hoặc Danh sách các thực thể. Chúng ta có thể truyền entity vào các hành vi điều khiển để thực hiện hành động CRUD (CRUD::Create, Read, Update, Delete).

Định nghĩa entity là gì?

.netTiers sử dụng khái niệm về thực thể cùng với các TableModule & Truyền dữ liệu đối tượng (DTO) Các Pattern biểu diễn cơ sở dữ liệu của bạn như các thực thể. Có nghĩa là, cho mỗi bảng trong cơ sở dữ liệu của bạn, thực thể sẽ được tạo ra cho bảng đó. DTO cho phép bạn vượt qua các đối tượng thông qua nhiều tầng trong khi vẫn duy trì cấu trúc lỏng lẻo kết thúc mở lớp thực thể, vì nó không phụ thuộc vào bất kỳ DataProvider.

.netTiers cũng sẽ cố gắng đi sâu vào quan hệ giữa các bảng với các bảng khác trong cơ sở dữ liệu và sẽ tạo ra thuộc tính con của các quan hệ. Điều này sẽ tạo ra toàn bộ miền thực thể. Hiện nay các loại quan hệ hỗ trợ là 1-1, 1-n, và n-n. Các quan hệ làm cho nó dễ dàng để trực tiếp làm việc với các entity và có đồ thị Object hợp lý. Có một số cách để tạo ra quan hệ nhất định, nhưng chúng ta sẽ thảo luận về các quy tắc trong phần cơ sở dữ liệu Model.

Ví dụ về Customer Entity: 
///An example object graph of a customer entity looks like this.
/// Customer Parent
///   Order 1:1
///    OrderDetails //1:M
///    ProductCollection //1:M
///   CustomerDemographics //1:M
///   CustomerDemographicsCollection_From_CustomerCustomerDemo //M:M

EntityBase

Tất cả các thực thể kế thừa từ hai lớp cha, lớp người sử dụng gọi là EntityBase.cs được thừa kế từ EntityBaseCore.generated.cs, lớp generated. Như đã đề cập trước đó, tất cả lớp generated sẽ được tạo ra, không sửa đổi các lớp này vì bạn sẽ bị mất khi bạn tạo lại mã.

Các lớp cơ sở thực hiện các hành vi cơ bản trên tất cả các thực thể. Lớp EntityBase cung cấp cho bạn truy cập độc quyền để thay đổi hành vi trong tất cả các thực thể. Bạn có thể ghi đè lên và những thay đổi này sẽ không bị ghi đè. Đây là cách để bạn có thể thực hiện thay đổi và mở rộng hành vi trong khi cùng một lúc, bảo vệ công việc của bạn.

Các lớp EntityBase cung cấp hành vi quản lý trạng thái sử dụng thuộc tính EntityState.

Thực thể trạng thái là gì?

Thực thể trạng thái cung cấp cách để theo dõi tình trạng hiện tại của thực thể trong đó là vòng đời thực thể, khác với các đối tượng vòng đời CLR. Có 4 EntityStates chính, tìm thấy trong liệt kê EntityState, Unchanged, Added, Changed, và Deleted. Bạn không cần theo dõi trạng thái, khi bạn thay đổi thuộc tính, hoặc tạo ra thực thể mới, hoặc đọc thực thể từ cơ sở dữ liệu. NetTiers sẽ tự động thay đổi trạng thái và theo dõi cho bạn.

/// <summary>
/// List of possible state for an entity.
/// </summary>
public enum EntityState
{
     /// <summary>
     /// Entity is read in from the database, unchanged
     /// </summary>
     Unchanged=0, 

     /// <summary>
     /// Entity is new and not yet in the database
     /// </summary>
     Added=1, 

     /// <summary>
     /// Entity has been modified
     /// </summary>
     Changed=2, 

     /// <summary>
     /// Entity has been deleted
     /// </summary>
     Deleted=3
 }

Vòng đời Entity

Giả sử bạn không có dữ liệu trong cơ sở dữ liệu, điều đầu tiên bạn sẽ làm là thêm dữ liệu vào cơ sở dữ liệu. Để làm điều này, bạn sẽ phải tạo ra thực thể mới. Hãy sử dụng các thực thể Customer mà chúng ta đã tạo ra từ cơ sở dữ liệu Northwind, và tạo ra thực thể Customer mới và bước qua các trạng thái khác nhau của thực thể, mà như đã nói trước là khác nhau hơn so với vòng đời đối tượng.

    ///STAGE 1: Added
    ///Create a new entity, whose EntityState is EntityState.Added               
    Customers customer = new Customers();
    customer.Address = "143/2 Ly Tu Trong";
    customer.City = "Da Nang";
    customer.Region = "Sea";
    customer.Phone = "0905042112";
    Response.Write(customer.EntityState); // EntityState.Added;
 
    ///Persist
    DataRepository.CustomersProvider.Save(customer);


    ///STAGE 2: Unchanged
    /// The EntityState has been set to EntityState.Unchanged
    ///Once we persist the entity, it will refresh the entity from the database
    ///If there is an identity column in your table that the entity represents
    /// then the new identity of the inserted value is returned as well.
    Response.Write(customer.CustomerID);
    Response.Write(customer.EntityState); // EntityState.Unchanged;

 
    ///STAGE 3: Changed
    /// By modifying a property the entity will automatically 
    /// change state to an EntityState.Changed state.
    customer.Region = "Under The Sea";
    Response.Write(customer.EntityState); // EntityState.Changed;
    DataRepository.CustomersProvider.Save(customer);
 

    ///STAGE 4: Deleted
    /// Two ways exist being in an EntityState.Deleted state for an Entity.
    /// MarkToDelete() method, or directly calling Delete in the repository.
    /// MarkToDelete() is mainly used when using the Save() method, 
    /// wanting to delete an entity which aggregated 
    /// and part of a Collection, a TList<Entity>.
    /// If you are working with a single entity as depicted, you would  
    /// just pass the entire entity into the DataRepository for Deletion.

    ///Using Delete Method Directly on the Entity
    DataRepository.CustomersProvider.Delete(customer);     

    ///Using Save Method in DataRepository with MarkToDelete()
    customer.MarkToDelete();
    Response.Write(customer.EntityState); // EntityState.Deleted;
    DataRepository.CustomersProvider.Save(customer);
 
    ///EntityState.Unchanged
    ///Say I want to delete all customers that have a city = Atlantis
    /// Whenever you get any entity items from the Database, once created 
    /// the state is immediately changed to EntityState.Unchanged
    TList<Customers> myList = DataRepository.CustomersProvider.GetByCity("Atlantis");

    for (int i = 0; i < myList.Count; i++)
    {
        Response.Write(myList[i].EntityState); // EntityState.Unchanged;
       myList.RemoveEntity(myList[i]);

        Response.Write(myList[i].EntityState); // EntityState.Deleted;
    }

     /// Now you've actually removed the entities from the list
     Response.Write(myList.Count); // Prints 0
 
     /// They are however moved to a DeletedItems collection
     Response.Write(myList.DeletedItems.Count); //Prints 1

     ///Will delete the items from the Database
     DataRepository.CustomersProvider.Save(myList);

     ///Or you can Iterate the list calling MarkToDelete();
     myList.ForEach(
        delegate(Customers c)
            {
                     c.MarkToDelete();
            }
        );
 
    ///Will persist all of the Deleted entities.
    DataRepository.CustomersProvider.Save(myList);

Hành vi Base State

Bạn có thể ghi đè lên hành vi mặc định nếu bạn muốn và quản lý bằng EntityState đã được sử dụng. Nếu bạn muốn sử dụng statemachine thay vì quản lý trạng thái. Nhìn chung, đó là cách tiếp cận linh hoạt cho phép bạn tùy chỉnh..

Ngoài ra còn có một số tính chất mô tả trạng thái thực thể như isDeleted, IsDirty, IsNew. Một điều khác cần lưu ý, là bạn có thể loại bỏ các cờ sau khi sử dụng MarkToDelete bằng cách gọi RemoveDeleteMark ().

Trích từ EntityBase.generated.cs

        /// <summary>
        ///    True if object has been <see cref="MarkToDelete"/>. ReadOnly.
        /// </summary>
        [BrowsableAttribute(false), XmlIgnoreAttribute()]
        public bool IsDeleted
        {
            get { return this.currentEntityState == EntityState.Deleted; }
        }


        /// <summary>
        ///        Indicates if the object has been modified from its original state.
        /// </summary>
        /// <remarks>True if object has been modified; otherwise False;</remarks>
        [BrowsableAttribute(false), XmlIgnoreAttribute()]
        public bool IsDirty
        {
            get
            {
                return this.currentEntityState != EntityState.Unchanged 
                            && this.currentEntityState != EntityState.Added;
            }
        }

        /// <summary>
        ///        Indicates if the object is new.
        /// </summary>
        /// <remarks>True if objectis new; otherwise False;</remarks>
        [BrowsableAttribute(false), XmlIgnoreAttribute()]
        public bool IsNew
        {
            get { return this.currentEntityState == EntityState.Added; }
            set { this.currentEntityState = EntityState.Added; }
        }


        /// <summary>
        ///        Indicates state of object
        /// </summary>
        /// <remarks>0=Unchanged, 1=Added, 2=Changed</remarks>
        [BrowsableAttribute(false), XmlIgnoreAttribute()]
        public virtual EntityState EntityState
        {
            get { return this.currentEntityState; }
            set { this.currentEntityState = value; }
        }


        /// <summary>
        /// Accepts the changes made to this object.
        /// </summary>
        /// <remarks>
        /// After calling this method <see cref="IsDirty"/> and <see cref="IsNew"/> are false.         
        /// <see cref="IsDeleted"/> flag remain unchanged as it is handled by the parent List.
        /// </remarks>
        public virtual void AcceptChanges()
        {
            this.bindingIsNew = false;
            this.currentEntityState = EntityState.Unchanged;
            OnPropertyChanged(string.Empty);
        }

        ///<summary>
        ///  Revert all changes and restore original values.
        ///  Currently not supported.
        ///</summary>
        /// <exception cref="NotSupportedException">This method throws exception.</exception>
        public abstract void CancelChanges();

        ///<summary>
        ///   Marks entity to be deleted.
        ///</summary>
        public virtual void MarkToDelete()
        {
            if (this.currentEntityState != EntityState.Added)
                this.currentEntityState = EntityState.Deleted;
        }


        ///<summary>
        ///   Remove the "isDeleted" mark from the entity.
        ///</summary>
        public virtual void RemoveDeleteMark()
        {
            if (this.currentEntityState != EntityState.Added)
            {
                this.currentEntityState = EntityState.Changed;
            }
        }

Triển khai Interface

Các thực thể tự thực hiện một số Interface để cung cấp đầy đủ các tính năng của các tầng sử dụng. Hai lớp đầu tiên là tùy chỉnh Interface netTiers., Còn lại là từ không gian tên System.ComponentModel và System.Runtime.Serialization.

Một số Interface:
  • IEntityId - Cung cấp một khóa chính đóng gói cho các thực thể.
  • IEntity-A - .NetTiers interface cung cấp tất cả các chức năng cần thiết cho thực thể netTiers..
  • IComparable - Thực hiện khả năng so sánh hai loại thực thể.
  • ICloneable - Thực hiện khả năng sao chép một thực thể
  • IEditableObject - Thực hiện khả năng cam kết hoặc rollback thay đổi một đối tượng được sử dụng như một nguồn dữ liệu.
  • IComponent - Triển khai chức năng theo yêu cầu tất cả các thành phần .Net System.ComponentModel..
  • INotifyPropertyChanged - Thông báo cho client giá trị thuộc tính đã thay đổi.
  • IDataErrorInfo - Cung cấp các chức năng để cung cấp thông tin lỗi tùy chỉnh giao diện người dùng.
  • IDeserializationCallback - Chỉ ra rằng một lớp sẽ được thông báo khi tuần tự của toàn bộ đồ thị đối tượng đã được hoàn thành.
Các generated view là gì? Chúng có phải là thực thể?

Các kiểu đối tượng Generated views không được coi là thực thể, mặc dù chúng có nhiều thuộc tính tương tự. Đối tượng View không duy trì trạng thái bởi vì chúng không được lưu lại vào cơ sở dữ liệu.

Thực thể Validation Rule Engine

Một trong những tính năng mạnh mẽ nhất mà. NetTiers cung cấp để quản lý tính toàn vẹn của dữ liệu là Quy tắc thực thể Engine. Nó thực hiện IDataErrorInfo trong lớp EntityBase.generated.cs. Nó cung cấp khuôn khổ cho việc quản lý quy tắc thực thể business và thông tin lỗi tùy chỉnh giao diện người dùng. Điều khiển như DataGridView tự động phát hiện các giao diện này và cung cấp các biểu tượng lỗi cùng với mô tả về lỗi.

Có một số tính năng hỗ trợ bạn trong việc quản lý quy tắc business. Có một số được xây dựng xác nhận sẵn sàng để sử dụng ra khỏi ô.
  • NotNull - Xác định nếu cột cơ sở dữ liệu chấp nhận giá trị null.
  • StringMaxLength - So sánh với độ rộng cột cho thuộc tính.
  • StringRequired - Xác định các cột cho phép các mục chuỗi rỗng.
  • MaxWords - Xác định xem thuộc tính đã exceeted số lượng tối đa của các từ
  • RegexIsMatch - Xác định xem thuộc tính hiện tại phù hợp với biểu thức chính
  • LessThanOrEqualToValue - Nhỏ hơn hoặc bằng với giá trị hiện tại của thuộc tính
  • LessThanValue - ít hơn giá trị hiện tại của thuộc tính
  • EqualsValue - Bằng giá trị hiện tại của thuộc tính
  • GreaterThanValue - Lớn hơn giá trị hiện tại của thuộc tính
  • GreaterThanOrEqualToValue - Lớn hơn hoặc bằng với giá trị hiện tại của thuộc tính
  • CompareValues ​​- So sánh giá trị của T sử dụng Comparer
  • InRange - Đảm bảo T là trong vòng một phút và tối đa của Phạm vi sử dụng Comparer.
Validation/ValidationRuleHandler.cs

        /// <summary>
        /// Delegate providing method sig that will process validation rules.
        /// </summary>
        /// <remarks>
        /// <para>
        /// The method handler should set the Description attribute of the 
        /// <see cref="ValidationRuleArgs"/> parameter so that a meaningful
        /// error is returned.
        /// </para><para>
        /// If the data is valid, the method must return true.  If  invalid,
        /// the Description should be set the false should be returned.
        /// </para>
        /// </remarks>
        public delegate bool ValidationRuleHandler(object target, ValidationRuleArgs e);

Ví dụ về Auto-Generated Rules

. netTiers sẽ tự động phát hiện các quy tắc áp dụng cho cơ sở dữ liệu để duy trì tính toàn vẹn dữ liệu. Tuy nhiên nó vẫn còn rất dễ dàng để bạn có thể thêm vào. Dưới đây là một ví dụ về quy tắc tự động thêm cho các thực thể Customer tôi đã làm việc.

protected override void AddValidationRules()
{
//Validation rules based on database schema.
ValidationRules.AddRule(Validation.CommonRules.NotNull,"CustomerID");

ValidationRules.AddRule(Validation.CommonRules.StringMaxLength,
    new Validation.CommonRules.MaxLengthRuleArgs("CustomerID",5));

ValidationRules.AddRule(Validation.CommonRules.NotNull,"CompanyName");

ValidationRules.AddRule(Validation.CommonRules.StringMaxLength,
    new Validation.CommonRules.MaxLengthRuleArgs("CompanyName",40));

ValidationRules.AddRule(Validation.CommonRules.StringMaxLength,
    new Validation.CommonRules.MaxLengthRuleArgs("ContactName",30));

ValidationRules.AddRule(Validation.CommonRules.StringMaxLength,
    new Validation.CommonRules.MaxLengthRuleArgs("ContactTitle",30));

ValidationRules.AddRule(Validation.CommonRules.StringMaxLength,
    new Validation.CommonRules.MaxLengthRuleArgs("Address",60));

ValidationRules.AddRule(Validation.CommonRules.StringMaxLength,
    new Validation.CommonRules.MaxLengthRuleArgs("City",15));

ValidationRules.AddRule(Validation.CommonRules.StringMaxLength,
    new Validation.CommonRules.MaxLengthRuleArgs("Region",15));

ValidationRules.AddRule(Validation.CommonRules.StringMaxLength,
    new Validation.CommonRules.MaxLengthRuleArgs("PostalCode",10));

ValidationRules.AddRule(Validation.CommonRules.StringMaxLength,
    new Validation.CommonRules.MaxLengthRuleArgs("Country",15));

ValidationRules.AddRule(Validation.CommonRules.StringMaxLength,
    new Validation.CommonRules.MaxLengthRuleArgs("Phone",24));

ValidationRules.AddRule(Validation.CommonRules.StringMaxLength,
    new Validation.CommonRules.MaxLengthRuleArgs("Fax",24));

}

Làm thế nào để thêm các quy tắc riêng?

Thêm quy tắc riêng là dễ dàng. Có một số cách để làm điều đó khi thuộc tính được expose. Đơn giản nhất có lẽ chỉ là ghi đè lên các phương thức trong thực thể của bạn AddRules() và thêm các quy tắc riêng cùng với những cái đã được tạo ra. Dưới đây là một ví dụ về thực thể Order từ Northwind generation.

Orders.cs -> Người dùng tập tin tùy biến cho lớp thực thể.

/// <summary>
/// Adds custom validation rules to this object.
/// </summary>
protected override void AddValidationRules()
{
    base.AddValidationRules();

    //Add custom validation rules
    ValidationRules.AddRule(Validation.CommonRules.StringRequired, "CustomerID");

     ValidationRules.AddRule(Validation.CommonRules.GreaterThanOrEqualToValue<Decimal?>,  new Validation.CommonRules.CompareValueRuleArgs<Decimal?> ("Freight", 0));

     ValidationRules.AddRule(
        Validation.CommonRules.LessThanOrEqualToValue<Decimal?>, 
                new    Validation.CommonRules.CompareValueRuleArgs<Decimal?>( 
                    "Freight", 200));

 
    ValidationRules.AddRule(ValidateOrderDate, "OrderDate");
}


/// <summary>
/// Validates the order date.
/// </summary>
/// <param name="target">The target.</param>
/// <param name="e">The e.</param>
/// <returns></returns>
private bool ValidateOrderDate(object target, Validation.ValidationRuleArgs e)
{
    if ((this.OrderDate ?? DateTime.MinValue) > DateTime.Today)
    {
        e.Description = "The Order Date must not be in the future.";
        return false;
    }

    return true;
}

Vì vậy, làm thế nào để xác nhận và thấy thông báo lỗi?

Cách đơn giản nhất để xác nhận là khi sử dụng thực thể duy nhất chỉ để gọi thuộc tính IsValid. Nó sẽ tự động kích hoạt tiến trình xác nhận. Bạn cũng có thể buộc tiến trình xác nhận bằng cách gọi Validate();

    Orders o = new Orders();
    o.OrderDate = new DateTime(2001, 8, 29);
    o.ShipAddress = "302 West Main Street";
    o.ShipCity = "Atlantis";
    o.ShipCountry = "Anywhere";
    o.ShipName = "Frank Sanders";
    o.ShipPostalCode = "55512";
    o.ShipRegion = "Under the Sea";

 
    o.Validate();
    ///Error property is a newline delimeted list of your broken rules.
    if (!o.IsValid)
        lblMessage.Text = o.Error; 

   ///you can actually access all of the rules that were broken on the entity.
   foreach(BrokenRule rule in o.BrokenRulesList)
   {
     lblMessage.Text = string.Format("<li>{0} - {1}</li>", 
        rule.Property, rule.Description);
   }

   /// Suppose we have a partner vendor that 
   /// processes orders for us, and we need 
   /// to validate all of today's orders. 
   /// Get today's orders and validate them.  
   TList<Orders> ordersList = GetOrdersFromVender();
    if (!ordersList.IsValid)
    {
        StringBuilder sb = new StringBuilder();
        sb.Append("<li>");
        foreach(Orders o in ordersList.InvalidItems)
        {
            sb.Append(o.Error.Replace("\n", "<li>"));
        }
        lblMessage.Text = sb.ToString();

    }

Sử dụng Collections trong .netTiers, TList & VList:

.netTiers có hai kiểu list chung mà nó độc quyền sử dụng cho các entity. TList và VList. TList là đặc trưng và đầy đủ nhất với kiểu thực hiện IEntity, đó là những thực thể được tạo ra từ bảng như trước đây đã nêu. VList là danh sách hạn chế các entity View không duy trì EntityState.

    Orders order = new Orders();
    order.OrderDate = new DateTime(2013, 5, 14);
    order.ShipAddress = "143 Ly Tu Trong";
    order.ShipCity = "Da Nang";
    order.ShipCountry = "VietNam";
    order.ShipName = "HoChiMinh";
    order.ShipPostalCode = "12345";
    order.ShipRegion = "Under the Sea";

    ///Index Of, Get's the location of the order in the list
    int index = ordersList.IndexOf(order);

    ///FindIndex
    ///Returns the integer value if 
    ///one of the criteria matches your predicate
    ordersList.FindIndex(
        delegate(Orders orders)
        {
            return orders.RequiredDate < DateTime.Today.AddDays(2);
        });
 
 
         ///Insert
    ///Useful if you want to insert an order in a specific location
    if (index < 0)
        ordersList.Insert(0, order);
 
    ///Add
    ///Appends an order to the list
    ordersList.Add(order);

 
    ///AddNew
    ///Appends a new order to the list
    ordersList.AddNew();
    ordersList[ordersList.Count - 1].OrderDate = DateTime.Today;

 
    ///RemoveEntity
    ///Removes the order from the list and places it in DeletedItems
    ordersList.RemoveEntity(order);
 
    ///RemoveAt
    ///Removes the first entry of the list
    ordersList.RemoveAt(0);
 
    ///RemoveAt
    ///Removes the entity where it exists
    ordersList.Remove(order);
 
    ///ListChanged
    ///Fires an event when the list has changed
    ordersList.ListChanged += 
      new System.ComponentModel.ListChangedEventHandler(ordersList_ListChanged);

 
    ///IsDeletedCount
    ///Returns the count of the DeletedItems Collection
    int deletedCount = ordersList.IsDeletedCount;
    Debug.Assert(deletedCount == ordersList.DeletedItems.Count);
 
    ///IsDirtyCount
    ///Returns the count of the items that have an 
    ///EntityState == EntityState.Changed
    int dirtyCount = ordersList.IsDirtyCount;
    Response.Write(string.Format("You have modified {0} entities.",dirtyCount));
 
    ///IsNewCount
    ///Returns the count of the items that have an 
    ///EntityState == EntityState.Added
    int newCount  = ordersList.IsNewCount;
    Response.Write(string.Format("You have added {0} entities.", newCount));
 
    ///FindAllBy
    ///Returns a new List of Entities that 
    /// match the FindAllByType
    ///FindAllByType.Contains, FindAllBy.StartsWith, FindAllByType.EndsWith
    TList<Orders> sList = ordersList.FindAllBy(TList<Orders>.FindAllByType.StartsWith, 
                        OrdersColumn.ShipCity, "Atl");
 
    TList<Orders> cList = ordersList.FindAllBy(TList<Orders>.FindAllByType.Contains,
                        OrdersColumn.ShipCity, "ant");

     TList<Orders> eList =ordersList.FindAllBy(TList<Orders>.FindAllByType.EndsWith,
                        OrdersColumn.ShipCity, "tis");

    ///FindAll
    ///Returns a new List of Entities that match using the Table Enum Columns
    TList<Orders> eqList = 
        ordersList.FindAll(OrdersColumn.ShipCity, "Atlantis");

 
    ///FindAll
    ///Returns a new List of Entities using a predicate
    TList<Orders> eqList2 = ordersList.FindAll(
        delegate(Orders o2){
            return 
                o2.OrderDetailsCollection.Count > 0 &&
                o2.OrderDate == DateTime.Today;
        });
 
    ///Exists
    ///Returns a bool if one of the criteria matches your predicate
    if (ordersList.Exists(
        delegate(Orders o3)
        {
            return
                o3.OrderDetailsCollection.Count > 0 &&
                o3.OrderDate == DateTime.Today;
        }))
    {
        Response.Write("There are orders today");
    }
 
    ///ToArray
    ///Creates an orders array from a list
    Orders[] orderArray = ordersList.ToArray();
 
    ///ToDataSet
    ///Creates a DataSet with children relationships from your TList.
    DataSet ds = ordersList.ToDataSet(true);
 
    /// Filter as a string
    /// Creates a view inside of your list using a case sensitive filter
    /// Great for cached items that you need to show
    /// different sets of entities based on criteria.
    ordersList.Filter = "ShipCity = 'Atlantis'";
    //ApplyFilter is automatically called on the set of the Filter property 
    //ordersList.ApplyFilter();
            ordersList.ForEach(
            delegate(Orders filteredOrder)
            {
                Debug.Assert(filteredOrder.ShipCity == "Atlantis");   
            });
 
    ///To Remove the filter, you simply call ResetFilter;
    ordersList.RemoveFilter();

    /// Filter using a Predicate delegate
    /// Great for needing to filter on items that 
    /// different sets of entities based on criteria.
    ordersList.ApplyFilter(GetValidAtlantisOrders);
    ordersList.ForEach(
    delegate(Orders filteredOrder)
    {
        Debug.Assert(filteredOrder.IsValid 
            && filteredOrder.ShipCity == "Atlantis");
    });

}//End Page_Load


    /// <summary>
    /// Gets the valid atlantis orders.
    /// </summary>
    /// <param name="o">The o.</param>
    /// <returns></returns>
    public bool GetValidAtlantisOrders(Orders o)
    {
        return (o.IsValid 
                && o.ShipCity == "Atlantis" 
                && o.OrderDetailsCollection.Count > 0
                && o.OrderDetailsCollection.IsValid);
    }
 
    void ordersList_ListChanged(object sender,                                            System.ComponentModel.ListChangedEventArgs e)
    {
        throw new Exception("The method or operation is not implemented.");
    }
 
  /// <summary>
  /// Gets the orders from vendor. Stub method, does nothing. 
  /// </summary>
  /// <returns></returns>
  public TList <Orders> GetOrdersFromVendor()
  {
     //Get Some orders from a vendor
       return new TList<Orders>();
  }   
}

Quản lý Entity Framework:

Trong ứng dụng thường có một số khía cạnh ứng dụng mà bạn phải làm để tối ưu hóa ứng dụng.

EntityFactoryBase

EntityFactoryBase là cấu trúc creational tồn tại để hỗ trợ cho việc tạo ra các thực thể của kiểu không thể biết trong thời gian chạy. Các entity đang/đã trích lập trong DataRepository trong phương thức Fill cho EntityProvider. Vì vậy, nếu tôi có DataRepository.MyEntityProvider, sẽ có phương thức gọi là Fill lấy IDataReader, TList (EntityCollection) và params row. Phương thức này sẽ hydrat các thực thể khi trở về DataRepository.

Phiên bản của template này cho phép bạn tạo các thành phần đối tượng business kế thừa từ các đối tượng thực thể. Vì các thành phần đối tượng hoạt động ở tầng trên cùng của lớp truy cập dữ liệu và thực thể. Khi DataRepository tạo ra các entity để sử dụng, nó không thể tạo ra các kiểu vì Dal không biết về các thành phần đối tượng business thông minh, chỉ có các đối tượng thực thể DTO. Vai trò của EntityFactory được sử dụng là khả năng để xác định nơi sản xuất sẽ được sử dụng để tạo các đối tượng được lấp đầy trong app/web.config.

Ví dụ:

entityFactoryType="Northwind.Entities.EntityFactory";
// OR 
entityFactoryType="Northwind.Entities.ComponentEntityFactory";

Mỗi factory sẽ sử dụng miền không gian của factory để tạo ra các kiểu unknow thời gian chạy bằng cách sử dụng Activator. Kiểu phát hiện này sẽ được lưu trữ và do đó bạn chỉ phải đối mặt với một hit Perf lần.

Có những sự kiện mà bạn có thể đăng ký trong tiến trình này để tiêm một số logic trước khi đối tượng được tạo . Điều này rất hữu ích nếu bạn muốn đính kèm sự kiện riêng đến thực thể.

EntityCache

Lớp EntityCache quản lý vòng đời của các entity mà bạn muốn không phải được truy vấn cho tất cả thời gian. Trong thực tế, lớp này chỉ đơn giản là kết thúc Enterprise Library Cache. EntLib cung cấp bộ nhớ đối tượng cache đầy đủ tính năng và cấu hình. Bộ nhớ cache thực thể có thể được sử dụng bởi bất kỳ đối tượng, và không phải là thực thể. Thông tin thêm có thể được tìm thấy ở đây: Library Caching Block

. NetTiers sẽ tạo cấu hình bộ nhớ cache mặc định tại thời gian chạy nếu không tồn tại, nhưng nó khuyến cáo bạn tạo cấu hình cho khối bộ nhớ đệm để tối ưu hóa các thiết lập bộ nhớ cache cho ứng dụng. Bộ nhớ cache thực thể có thể dễ dàng được cấu hình bằng cách chỉ công cụ Enterprise Library Configurator  tại app/web.config. Bao gồm mẫu thiết lập mặc định entlib.config trong dự án MyNamespace.UnitTest.

IEntityCacheItem

Khi  interface đánh dấu này được áp dụng cho một thực thể, các tổ chức sẽ tự động được đặt vào bộ nhớ cache.  Interface cung cấp suốt vòng đời và gọi lại các thông số được sử dụng để quản lý bộ nhớ đệm các entity. Đây là  interface mà bạn sẽ phải áp dụng cho mình đến các thực thể ở cấp lớp cao.

EntityLocator

EntityLocator trên đầu trang của lớp Locator Microsoft Patterns và Practices Group ObjectBuilder Framework. Nơi chịu trách nhiệm cho việc tạo ra đối tượng WeakReference'd Object Store của bạn được xử lý một số lượng lớn các entity, trong đó phần nhiều giống bản ghi, chúng sẽ trả lại cho bạn cùng đối tượng cho tất cả các tài liệu tham khảo cho đến khi tổ chức được kéo dài đến các DataRepository. 

Tính năng này đã được kích hoạt trong app/web.config dưới enableEntityTracking="true/false" 

EntityManager

EntityManager là chất keo giữ tất cả, và cần được coi là điểm khởi đầu cho hầu hết các tính năng, ngoại trừ các EntityCache. Khi đối tượng sắp được tạo và DataRepository.Provider.EntityTracking được kích hoạt, EntityManager được gọi. EntityManager chứa đối tượng EntityLocator duy nhất và bộ sưu tập các đối tượng EntityCache, cho tất cả cung cấp bộ nhớ cache thực thể khác nhau. Nhiều khả năng, mặc dù có thể chỉ có một đối tượng EntityCache duy nhất trong đó.

EntityManager chứa phương thức LocateOrCreate xác định nếu thực thể đã tồn tại và hiện đang được tham chiếu, nếu như vậy, thì trả về thực thể, nếu không, tạo một cái mới bằng cách sử dụng nơi sản xuất thực thể xác định và bắt đầu theo dõi các thực thể.

Vậy là Tôi đã giới thiệu chi tiết Lớp Entity, bài viết tiếp theo Tôi sẽ giới thiệu Lớp Data, các cách truy cập dữ liệu

Nguồn bài viết: DOTNET.VN

BÌNH LUẬN BÀI VIẾT

Bài viết mới nhất

LIKE BOX

Bài viết được xem nhiều nhất

HỌC HTML