📜 ⬆️ ⬇️

Linq basics. Linq and n-tier architecture

Microsoft has provided a new, easy-to-learn and very powerful and flexible extension of .NET languages ​​for data processing called Linq.

How in multilevel applications to design data provider so that to receive a dial-up of objects?

For example , there is a table tbCustomers ((Int64) CustID, (String) Name, (int32) Age) and there is a class Customers:

public class Customers
{
    private Int64 _CustID;
    public Int64 CustID
    {
        get { return _CustID; }
        set {_CustID = value ; }
    }

    private string _Name;
    public string Name
    {
        get { return _Name; }
        set {_Name = value ; }
    }

    // Int32 type is null tolerable
    private int32 ? _Age;
    public int32 ? Age
    {
        get { return _Age; }
        set {_Age = value ; }
    }

    // Initializers
    public Customers ()
    {
    }
   
    public Customers ( Int64 CustID, string Name, Int32 ? Age)
    {
        _CustID = CustID;
        _Name = Name;
        _Age = Age;
    }

    // Get a set of objects from the data provider
    public static List < Customers > GetCustomers ()
    {
        return CustomersData .GetAllCustomers ();
    }
}

and you need to get a set of Customers from the vendor .

Standard solution to this issue in. NET 2.0 is the use of the System namespace . Data . SqlClient :

public static class CustomersData
{
    // Use SqlClient
    public static list < Customers > GetAllCustomers ()
    {
        List < Customers > lst = new List < Customers > ();
        using ( SqlConnection conn = new SqlConnection ( "Data Source = ..." ))
        {
            conn.Open ();
            SqlCommand cmd = new SqlCommand ( "SELECT CustID, Name, Age FROM tbCustomers" , conn);
            SqlDataReader reader = cmd.ExecuteReader ();
            while (reader.Read ())
            {
                lst.Add ( new Customers (( Int64 ) reader [ "CustID" ], ( String ) reader [ "Name" ], ( Int32 )? reader [ "Age" ]));
            }
        }
        return lst;
    }
}

When using Linq, we can get a set of data from anonymous types using the object's initializer, i.e.

public static class CustomersData
{
    // Using Linq
    public static list < Customers > GetAllCustomers ()
    {
        LinqDcDataContext db = new LinqDcDataContext ();
        IEnumerable < Customers > result = db.tbCustomers.Select (c => new Customers (c.CustID, c.Name, c.Age));
        // Set IEnumerable <Customers> to List <Customers>
        return new List < Customers > (result);
    }
}




Original Linq article in n-tier architecture

')

Source: https://habr.com/ru/post/15113/


All Articles