Thursday, 25 April 2013

Contexts and Entities in EDMX File in Entity Framework

Contexts and Entities in EDMX File in Entity Framework

Contexts and Entities in EDMX play a vital role and you must understand the purpose of these. Context contains all the logic for interacting with database and Entities represent database tables. Entites region contain public partial classes and public properties. Lets discuss it in detail:

When you create any EDMX file, follwing files are generated with it.

Model1.edmx
Model1.tt
Model1.Context.tt
Model1.Designer.cs
Model1.edxm.diagram
Model1.Designer.cs

Automatic code is generated in this file which contains context and entities if the "Code Genereation Strategy" is set to Default from None.

Also some points to note for this file

1. Manual changes to this file may cause unexpected behavior in your application.
2. Manual changes to this file will be overwritten if the code is regenerated.


Contexts and Entities in Model1.designer.cs

ObjectContext

If you open Model1.designer.cs, you can see two main regions, Contexts and Entities. expand contexts region. You can see partial class with suffix ‘entities’ and derived from ObjectContext class.

This class represents EntityContainer which you can see from XML view of Model1.edmx or from EDM property window. You can call this as context class.

This class is the primary class for interacting with entity objects and database. An instance of the ObjectContext class encapsulates the connection to the database, metadata that describes the model, and an ObjectStateManager object that tracks objects during create, update, and delete operations.

ObjectSet

Each EntitySet in context class is a type of ObjectSet<> that wraps the entity. e.g. ObjectSet.

EntityType

If you expand ‘Entities’ region, you can see many partial classes that are derived from EntityObject. This classes are EntityTypes of you model.

EntityType is a datatype in the model. You can see each EntityType for your conceptual model in XML. If you expand EntityType node in XML, you can see each properties and its type and other info.

EntityContainer

EntityContainer is a wrapper for EntitySets and AssociationSets. It is critical entry point for querying the model.

EntitySet

EntitySet is a container for EntityType. It is set of same entitytype. You can think it like db table.

AssociationSet

AssociationSet defines the relation between each EntitySet.

Model1.Context.tt is a context template file and Model1.tt is entities template file. 

Model1.tt and Model1.Context.tt templates, generate model entities and context. 

Model1.Context.tt: It produces a strongly typed ObjectContext for the Model1.edmx

Model1.tt: It is responsible for generating a file for each EntityType and ComplexType in the Model1.Context.tt.

Wednesday, 24 April 2013

How to convert an XML document into String in C#?

How to convert an XML document into String in C#?
 
Sometimes we come into the need where we have an XML file and we have to save that file in form of C# string. Well, converting XML document in string in C# is very easy. I will use XDocument class to do this job. With following steps you can easily do this with few lines of code in C#?
 
Step 1: Include namespace System.Xml.Linq.
 
using System.Xml.Linq;
 
Step 2: Load XML file in XDocument using following line of C# code.
 
var xDocument = XDocument.Load(@"C:\MyXMLFilePath.xml");
 
Step 3: Convert the xml into string
 
string xml = xDocument.ToString();
 
Now you can use this xml string wherever required.

Scaler and Navigation Properties in ADO.NET Entity Framework


Scaler and Navigation Properties in ADO.NET Entity Framework

Entities in ADO.NET Entity Framework can have two types of properties, Scalar properties and Navigation properties. 

Scalar Properties: Scalar properties are properties whose actual values are contained in the entity. 
Navigation Properties: Navigation properties are pointers to other related entities. Basically it is equivalent to a foreign key relationship in a database. 

Example of Scaler and Navigation Properties:

I will take an example here to make my defination more clear. Suppose there is Student table in database which has columns like StudentID, StudentName and StandardID. There is another table Standard which has StandardID, StandardName columns. Here StandardID is the forieng key. Now lets create and EDMX from these two tables. EDMX will have two entities Student and Standard which will look like following:

EDMX Entity of Student

Student              --Entity Name
-----------
StudentID          --Scaler Property
StudentName   --Scaler Property
StandardID       --Scaler Property
-----------
Standard           --Navigation Property

EDMX Entity of Standard

Standard               --Entity Name
-----------
StandardID           --Scaler Property
StandardName    --Scaler Property
-----------

Student entity has scalar properties e.g. StudentId, StudentName, StandardID. These correspond with the Student table columns.  

The Student has Standard property as navigation property that will enable application to navigate from a Student to related Standard entity. 

Modelling Approaches for Entity Framework: Database First, Model First, Code First


Modelling Approaches for Entity Framework: Database First, Model First, Code First

While working with ADO.NET Entity Framework, you have 3 types of modelling approaches which are:

1. Database First
2. Model First
3. Code First

Lets discuss these Entity Framework modelling approaches in detail.

1. Database First Modelling Approach

When you generate EDMX from existing database, then it is a Database First approach. So in Database First approach, when you add ADO.NET Entity Data Model, you should select ‘Generate from database’ instead of ‘Empty Model’.

2. Model First Modelling Approach

In Model First approach, you create Entities, Relationships, and Inheritance hierarchies directly on the design surface of EDMX. So in Model First approach, when you add ADO.NET Entity Data Model, you should select ‘Empty Model’ instead of ‘Generate from database’.

After creating required entities, associations and inheritance on design surface of the empty model, you can use designer’s context menu option ‘Generate database from model’. It will not generate new database from model. It will only give you DDL to execute in existing database and it is up to you to execute this DDL.

3. Code First Modelling Approach

In Code First approach, you avoid working with visual model designer (EDMX) completely. You write your POCO classes first and then create database from these POCO classes. Developers who follow the path of Domain-Driven Design (DDD) principles, prefer to begin by coding their classes first and then generating the database required to persist their data.  

DbContext and DbSet: There are two new types introduced for Code First approach, DbContext and DbSet. DbContext is a simplified alternative to ObjectContext and is the primary object for interacting with a database using a specific model. DbSet is a simplified alternative to ObjectSet and is used to perform CRUD operations against a specific type from the model in Code First approach.

Tuesday, 23 April 2013

How to show value of attributes of child nodes of an element in C#?

How to show value of attributes of child nodes of an element in C#?
 
Lets say you have following XML and you have to fetch IDs of Element tags which are under Segments/Segment/Elements. In this case you have to use SelectNodes method to reach upto desired nodes and then take it to the XMLNodeList. Iterate the list check its child nodes and get the attributes of child nodes. I think below code can clear what I am trying to say.
 
My XML File
 
<?xml version="1.0" encoding="utf-8"?>
    <Segments>
        <Segment ID="AAA">
            <Elements>
                <Element ID ="11" />
                <Element ID ="22" El/>
                <Element ID ="33" />
            </Elements>
         </Segment>
    </Segments> 
  
My C# code
 
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.Load(MyXMLFileLocation);
XmlNodeList xnList = xmlDocument.SelectNodes(/Segments/Segment[@ID='AAA']/Elements);
foreach (XmlNode xn in xnList)
{
    if (xn.HasChildNodes)
    {
        foreach (XmlNode childNode in xn.ChildNodes)
        {
            Console.Writeline(childNode.Attributes["ID"].Value);
         }
    } 
}

5 things to remember during an exit interview

5 things to remember during an exit interview
 
If you have resigned from a company and you are being called by HR for exit interview, you should face HR very politely and maintain a positive attitude. Here are some points I wanted to discuss with you on exit interviews.
 
1. Maintain your composure: You might come across very trivial questions but maintaining your composure is very critical, no matter how irrelevant you feel they might be. Be graceful and witty while answering tricky questions.
 
2. Emphasis on your experience: Discuss your experiences and key learning from them. Always mention about the opportunities those were given to you and how you were able to perform on them, which has enhanced your skills for future endeavours.
 
3. Don’t be negative:  Focus on the key learning from difficult situations at the work place. You should portray that every crisis had given an opportunity for you to be adaptable in different situations and be a quick fixer to any given problem.
 
4. Comments should be constructive: Be honest but polite while putting across your grievances. Instead of accusing anyone or any process, try giving examples on how it can be improved for better results.
 
5. Don’t take out personal grudge: It’s better to express your problems in a non-personal way rather pin-pointing it to any individual. Remember, it is unnecessary for you to comment on someone (negatively) who you are not going to see for much longer.

How to crack a Telephonic Interview? Things to keep in mind while Telephonic Interview

How to crack a Telephonic Interview? Things to keep in mind while Telephonic Interview
 
A telephonic interview is usually organised to short-list candidates, to minimise the cost of conducting face-to-face interviews or to screen outstation candidates.
 
This is an important step for both the interviewer and the interviewee. Just as a personal interview, there are some basic dos and don’ts. It is very critical to follow these as the difficult task here is to impress the interviewer on the phone and hold their attention for the entire conversation.Therefore:
 
Be serious: It is a job interview at the end of the day. So first rule is that one must treat a telephonic interview just as one would treat a face-to-face meeting.This means keeping your resume handy, making sure you get the name and designation of the interviewer right and most importantly avoid multitasking.
 
The same rule also applies to an interviewer. The interviewer must spend some time before the call to study the resume and also must ensure that they are not distracted by any other work at that point in time.
 
Avoid distractions: It is important to choose a quiet place to take the call. You don’t want to be distracted by background noise. If possible use a landline to avoid call drops. If you are using your mobile phone, ensure that your call-wait facility is switched off.
 
For interviewer it is equally important to show seriousness. Don’t interrupt the call. This can be very discouraging to an interviewee.
 
Maintain the tone: The difficult task in a telephonic interview is that one needs to put forth their best voice. Yes, that’s right. That’s the only interface you have with your interviewer. So maintain a normal tone, don’t get excited and more importantly don’t raise your voice at any given point. Further it is important that the candidate speaks slowly and clearly.
 
Be positive: You have to be extra careful about expressing the right attitude. So, say your ‘hello’ with a smile. Studies have shown that smiling on the phones creates a positive image. Also, it kind of adds a spring to your voice, makes you sound professional and confident.
 
Listen intently: Listening attentively is an important aspect of an interview. This is more so in case of a telephonic interview. It is important to listen carefully and answering honestly. On a telephone any slight hesitation is evident. However, don’t jump to answer a question immediately. Listen carefully and articulate it well before saying out loud.
 
Lastly, don’t rush through the interview. Take your time, sound prepared, take notes, if required. This will help you to create a positive image. Also, remember since it’s a telephonic interview you get a chance to keep all the information you may require handy. This could be your resume, notes about the company, job profile and so on. This is your cheat sheet – use it wisely.