LINQ

EDMX(Entity Data Model XML)

When ever we generate .edmx file, That can contain AESModel.Context.tt and AESModel.tt templates.

AESModel.Context.tt
With in the AESModel.Context.tt file,There is another class with name AESModel.Context.cs. This class contains DBContext Entities.This DbContext Entities class inherit from DbContext base class.
This Context class Contains all Model class DbSet<>.

AESModel.tt
This  AESModel.tt template contains all class(table) files with field proporties. 

Note :- For Updating Model from data base, Right click on edmx diagram and update.If changes not applied,Right click on .tt template and take option Run Custom Tool.

Adding SP's and Views

---> Add or Update Stored procedures to edmx like table
---> Open edmx designer view
---> go to  View -- Other Wondow -- Entitiy Data Model Browser
---> Related function will be generated under Function Imports Folder
---> We can able to edit function and click ok OK.
---> go to Solution Explorer and Build the application
---> SP related code and Model Class will be displayed in edmx file.

Here is the Model Browser.
Here is the Solution Explorer,After adding Stored Procedures and Tables.

Join two table using LINQ
var JoinTable=(from c in objDataBaseModel.tblTable1
                      join emp in objDataBaseModel.tblTable2
                      on c.tblTable1ID equals emp.tblTable2ID select c).FirstOrDefault();
Lambda Expression
A lambda expression is a anonymous function,It's mostly used to create deligates in LINQ.
Simply says,It's a method without declaration i,e Access modifiers and return value declaration and name.
Why lambda?
Convenience. It's a shorthand that allows you to write a method in the same place you are going to use it. Especially useful in places where a method is being used only once, and the method definition is short. It saves you the effort of declaring and writing a separate method to the containing class.
Benefits: 
1. Reduced typing. No need to specify the name of the function, its return type, and its access modifier. 
2. When reading the code you don't need to look elsewhere for the method's definition. 

Lambda expressions should be short. A complex definition makes the calling code difficult to read.
Parameters => Executed code

     n=>n%2==1
  •          n is the input parameter
  •          n % 2 == 1 is the expression
List<int> numbers = new List<int>{11,37,52};

List<int> oddNumbers = numbers.where(n => n % 2 == 1).ToList();

//--Saving Part
EmpContext objContext=new EmpContext();
Customer Obj=new Customer();
Obj.CustomerName="SHANKAR";
Obj.CustId=101;
ObjContext.Customers.AddObject(obj);
ObjContext.SaveChanges();

//-----Update Part
CustomermytestEntities objContext = new CustomermytestEntities();
Customer objCustomer = (Customer)objContext.Customers.FirstOrDefault();
objCustomer.CountryCode = "IND";
objContext.AcceptAllChanges();

//--  Delete Part
CustomermytestEntities objContext = new CustomermytestEntities();
Customer objCustomer = (Customer)objContext.Customers.FirstOrDefault();

objContext.DeleteObject(objCustomer);

IEnumerable
If we implement IEnumerable interface in our own class then we can loop through all class objects using foreach loop.
Store set of integer variables using IEnumerable
static void Main(string[] args)
{
IEnumerable<int> Values = from value in Enumerable.Range(1, 10) select value;
            foreach (int a in Values)
            {
                Console.WriteLine(a);
            } 

            Console.ReadLine();
 }
we will search a list using a LINQ query and we will go through all values using a foreach loop.
static void Main(string[] args)
        {
             List<string> List = new List<string>();
                List.Add("Sourav");
                List.Add("Ram");
                List.Add("shyam");
                List.Add("Sachin");
                IEnumerable names = from n in List where (n.StartsWith("S")) select n;

                foreach (string name in names)
                {
                    Console.WriteLine(name);
                }

                Console.ReadLine();
            }


        }
Now Implement IEnumerable in C#
class Test : IEnumerable
{
    Test[] Items = null;
    int freeIndex = 0;
    public string Name { get; set; }
    public string Surname { get; set; }
    public Test()
    {
        Items = new Test[10];
    }
    public void Add(Test item)
    {
        Items[freeIndex] = item;
        freeIndex++;
    }
    // IEnumerable Member
    public IEnumerator GetEnumerator()
    {
        foreach (object o in Items)
        {

            if (o == null)
            {
                break;
            }
            yield return o;
        }
    }

}

class Program
    {
        static void Main(string[] args)
        {          

            Test t1 = new Test();
            t1.Name = "Sourav";
            t1.Surname = "Kayal";

            Test t2 = new Test();
            t2.Name = "Ram";
            t2.Surname = "Das";
           
            Test myList = new Test();
            myList.Add(t1);
            myList.Add(t2);
            foreach (Test obj in myList)
            {
                Console.WriteLine("Name:- " + obj.Name + "Surname :- " + obj.Surname);
            }
            Console.ReadLine();
        }
    }
We can see that in the Test class we implemented the IEnumerable interface. Within the constructor we are creating a few objects of the Test class and added a method to add the objects of the Test class one by one. The GetEnumerator method will return an object of the Test class one by one because we are using yield.

Yield : yield‘ keyword is used in an Iterator block to provide a value to the enumerator object or to signal the end of an iteration.

       foreach (Product product in products)
        {
            yield return product;

        }
        /***********Another one**********/
return products.ToList<Product>();
--------------------------------------------------------------------

  • IEnumerable,ICollection,IQuaryable,IList are interfaces in the .NET framework used the most often.
  • IEnumerable is the base of all interfaces.
  • IEnumerable interface is used when we want to iterate among our classes using a foreach loop.
  • Every collection inside the .Net Framework implements the IEnumerable interface.
It provides read-only access to collections. We cannot change any item inside an IEnumerable List. It provides a sort of encapsulation in cases where we don't want our list to be changed.
If we are dealing with some SQL queries dynamically then it also provides lazy evaluation. That means the queries will not be executed until we explicitly need them.
ICollection

The ICollection interface is inherited from the IEnumerable interface which means that any class that implements the ICollection interface can also be enumerated using a foreach loop. In the IEnumerable interface we don't know how many elements there are in the collection whereas the ICollection interface gives us this extra property for getting the count of items in the collection. The ICollection interface contains the following: 
  • Count Property
  • IsSynchronized Property
  • SyncRoot Property
  • CopyTo Method
The Count property is used for maintaining the count of elements in the list whereas the IsSysnchronized and SyncRoot properties help to make the collection thread-safe. The CopyTo method copies the entire collection into an array. 
The generic version of this interface provides Add and Remove methods also. 
 IList

The IList interface implements both ICollection and IEnumerable interfaces. This interface allows us to add items to and remove items from the collection. It also provides support for accessing the items from the index. This interface has more power than the preceding two interfaces.

The IList interface contains the following:
  1. IsFixedSize Property
  2. IsReadOnly Property
  3. Indexer
  4. Add Method
  5. Clear Method
  6. Contains Method
  7. Indexof Method
  8. Insert Method
  9. Remove Method
  10. RemoveAt Method
The IList interface has one indexer by which we can access any element by its position and can insert an element and remove an element at any position.
IQuaryable
  • System.Linq Namespace
  • Derives from IEnumerable
  • While querying data from database, IQueryable execute select query on server side with all filters. Hence does less work and becomes fast.
  • LINQ to SQL queries.
  • when querying data from out-memory (like remote database, service) collections.

No comments: