• Wriju's BLOG

    Windows Phone 7 : Check the power status

    • 0 Comments

    You might need to check if your phone is connected to power or running in battery.

    //Check Power Status
    var power = Microsoft.Phone.Info.DeviceStatus.PowerSource;
    textBlock1.Text = power.ToString();
    

    Namoskar!!!

  • Wriju's BLOG

    Windows Azure Accelerator for Web Roles Released

    • 0 Comments

    WAAWebRoles.Logo

    Windows Azure Accelerator for Web Role released recently. Please check http://waawebroles.codeplex.com/. This would allow you to deploy multiple websites to a web role.

    There is a Channel 9 video available Getting Started with the Windows Azure Accelerator for Web Roles

    Namoskar!!!

  • Wriju's BLOG

    Channel 9 Video on Entity Framework 4.1

    • 0 Comments

    Published the video on ADO.NET Entity Framework 4.1 Code First Development video. This covers quickly the basic features if this amazing product.

    image

    Check it out at http://channel9.msdn.com/posts/EF41CodeFirst

    The code used for the demo is

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Data.Entity;
    using System.ComponentModel.DataAnnotations;
    
    namespace EF41CodeFirst_BDotnet
    {
        //Dept Class
        public class Dept
        {
            public Dept()
            {
                EmpDepts = new List<EmpDept>();
            }
            [Key] //Primary Key column
            public int MyId { get; set; }
            public string DeptName { get; set; }
            public string Location { get; set; }
    
            //For 1 to Many with EmpDept
            public virtual ICollection<EmpDept> EmpDepts { get; set; }
        }
    
        public class EmpDept
        {
            public int EmpDeptId { get; set; }
            public string EmpName { get; set; }
    
            //For foreign key
            public virtual Dept Dept { get; set; }
        }
    
        //Context to initialize connection using DbContext as base class
        public class HRContext : DbContext
        {
            public DbSet<Dept> Depts { get; set; }
            public DbSet<EmpDept> EmpDepts { get; set; }
        }
        
        class Program
        {
            static void Main(string[] args)
            {
                //Drop the database if model changes
                Database.SetInitializer<HRContext>(new DropCreateDatabaseIfModelChanges<HRContext>());
    
                //Adding values to the database
                using (var ctx = new HRContext())
                {
                    var d1 = new Dept() { DeptName = "Programming" };
                    var d2 = new Dept() { DeptName = "IT" };
    
                    new List<EmpDept>
                    {
                        new EmpDept(){EmpName = "Wriju", Dept = d1},
                        new EmpDept(){EmpName = "Saswati", Dept = d1},
                        new EmpDept(){EmpName = "Writam", Dept = d2},
                        new EmpDept(){EmpName = "Wrishika", Dept = d2},
                        new EmpDept(){EmpName = "Sreemoyee", Dept = d1},
                        new EmpDept(){EmpName = "Bingo", Dept = d1}
                    }.ForEach(e => ctx.EmpDepts.Add(e));
    
                    ctx.SaveChanges();
    
                    //Selecting data using Lazy Loading
                    var q = from d in ctx.Depts
                            select d;
    
                    foreach (var dep in q)
                    {
                        Console.WriteLine(dep.DeptName);
                        Console.WriteLine("+++++++++++++++++++++++++");
                        foreach (var e1 in dep.EmpDepts)
                        {
                            Console.WriteLine(e1.EmpName);
                        }
                        Console.WriteLine();
                    }
                }
            }
        }
    }
    

    Namoskar!!!

  • Wriju's BLOG

    Cost of My Windows Azure Application : Pricing Calculator

    • 0 Comments

    Often question comes to our mind “how to determine the cost of Azure application”. Now the pricing calculator is more interactive and easy to use. Sliders would help you determine the required numbers,

    image

    http://www.microsoft.com/windowsazure/pricing-calculator/

    Namoskar!!!

  • Wriju's BLOG

    Code First EF 4.1 : Table per Hierarchy

    • 0 Comments

    Concept of Table Per Hierarchy (TPH) is to implement polymorphism and to de-normalize the relational database via inheritance. The entire hierarchy is mapped to a single database table holding all the properties of all the classes. The database then would create a column called “[Discriminator]” to hold the specific type. In Code First this is default behavior and we do not have to do anything extra.

    TPH is the simplest and possibly the fastest approach. Code First just amazingly supports it.

    If we consider the below diagram of Animal, Mammal and Reptile. Here Animal is the abstract base class holding common properties.

    image

     This finally would get converted into a table as below (notice the additional [Discrminator] column which is NOT NULL)

    image

    To have this we need the below code

    public abstract class Animal
    {
        public int AnimalId { get; set; }
        public string Name { get; set; }
    }
    
    public class Reptile : Animal
    {
        public double Length { get; set; }
    }
    
    public class Mammal : Animal
    {
        public double Weight { get; set; }
        public bool IsMarried { get; set; }
    }
    
    public class AnimalContext : DbContext
    {
        public DbSet<Animal> Animals { get; set; }
    }
    

    To add data

    To add data to Reptile

    using (var ctx = new AnimalContext())
    {
        var Rep = new Reptile() { Name = "Snake", Length = 10.0 };
        ctx.Animals.Add(Rep);
        ctx.SaveChanges();

    To add data to Mammal

    using (var ctx = new AnimalContext())
    {
        var Mam = new Mammal() { IsMarried = true, Name = "Adam", Weight = 100.0 };
        ctx.Animals.Add(Mam);
        ctx.SaveChanges();
    

    After adding data would be saved as below

    image

    Querying data

    We can query data in various ways,

    var q = from a in ctx.Animals.OfType<Mammal>()
            select a;
    foreach (var k in q)
    {
        Console.WriteLine(k.Name);
    }
    

    We can also use Entity SQL with “OFTYPE”.

    Now the the column [Discriminator] can be altered through FluentAPI

    image

    This would create a column in the database as “AnimalType” and for each entry of Mammal add “M” and Reptile add “R”.

    image

    TPH anyways violets the third normal form and has serious data integrity issue and for a long term perspective this is not manageable. But still the simplest approach.

    Namoskar!!!

  • Wriju's BLOG

    Using ADO.NET EF 4.1 Code First with existing Database

    • 0 Comments

    Most of the time questions comes to our mind about EF 4.1 Code First whether or not can we use it with already available database? Simple answer is YES.

    I have very few personal view on it. I have seen in most of my application development scenario, database gets designed and created before and then evolves as application and requirements. So I expect to use Code First with already created database.

    This is how we can,

    image

    Step 1: We will go for the database-first approach and create our EDMX.

    image

    Step 2: Right click on the edmx and then choose “Add Code Generation Item…

    image

    Step 3: Select “ADO.NET DbContext Generator”. Then delete the .edmx file from your project.

    After that you need few small but important changes,

    Change 1 : Add the connection string (if using SQL Server)

    image

    Change 2 : The tables you are using in your code (check all the DbSet<T> in your context) and add their corresponding onModelCreating code

    image

    Then your code should run without any trouble,

    image

    Namoskar!!!

  • Wriju's BLOG

    Code First EF 4.1 : Querying Many to Many Relationship

    • 0 Comments

    In continuation to my previous post on how to create one to many, let’s see how can we query it.

    We will use the same code base and query it

    Option 1

    When we want to query it normally like below

    var emps = ctx.Emps
                .Where(e => e.EmpId == 1)
                .SelectMany(e => e.Projects, 
                        (em, proj) => new 
                        {
                            em.EmpName, 
                            proj.ProjectName
                        });
    

    The generated object graph would look like

    image

    Option 2

    Whereas if we want to write our query as below

    var em = from e in ctx.Emps.Include(p => p.Projects)
                where e.EmpId == 1
                select e;
                

    This case object graph is more complicated

    image

    Generated SQL

    Interestingly both the cases the generated SQL is same

    SELECT 
    [Project1].[EmpId] AS [EmpId], 
    [Project1].[EmpName] AS [EmpName], 
    [Project1].[C1] AS [C1], 
    [Project1].[ProjectId] AS [ProjectId], 
    [Project1].[ProjectName] AS [ProjectName]
    FROM ( SELECT 
    	[Extent1].[EmpId] AS [EmpId], 
    	[Extent1].[EmpName] AS [EmpName], 
    	[Join1].[ProjectId] AS [ProjectId], 
    	[Join1].[ProjectName] AS [ProjectName], 
    	CASE WHEN ([Join1].[Project_ProjectId] IS NULL) THEN CAST(NULL AS int) ELSE 1 END AS [C1]
    	FROM  [dbo].[Emps] AS [Extent1]
    	LEFT OUTER JOIN  (SELECT [Extent2].[Project_ProjectId] AS [Project_ProjectId], [Extent2].[Emp_EmpId] AS [Emp_EmpId], [Extent3].[ProjectId] AS [ProjectId], [Extent3].[ProjectName] AS [ProjectName]
    		FROM  [dbo].[ProjectEmps] AS [Extent2]
    		INNER JOIN [dbo].[Projects] AS [Extent3] ON [Extent3].[ProjectId] = [Extent2].[Project_ProjectId] ) AS [Join1] ON [Extent1].[EmpId] = [Join1].[Emp_EmpId]
    	WHERE 1 = [Extent1].[EmpId]
    )  AS [Project1]
    ORDER BY [Project1].[EmpId] ASC, [Project1].[C1] ASC

    Namoskar!!!

  • Wriju's BLOG

    Code First EF 4.1 : Building Many to Many Relationship

    • 8 Comments

    Since we do not have any designer question might arise how can we create Many to Many relationship in Code First 4.1. Here it is

    public class Emp
    {
        public Emp()
        {
            Projects = new HashSet<Project>();
        }
    
        public int EmpId { get; set; }
        public string EmpName { get; set; }
        public ICollection<Project> Projects { get; set; }
    }
    
    public class Project
    {
        public Project()
        {
            Emps = new HashSet<Emp>();
        }
    
        public int ProjectId { get; set; }
        public string ProjectName { get; set; }
        public ICollection<Emp> Emps { get; set; }
    }
    
    public class EmpContext : DbContext
    {
        public DbSet<Emp> Emps { get; set; }
        public DbSet<Project> Projects { get; set; }
    }
    
    class Program
    {
        static void Main(string[] args)
        {
            var p1 = new Project() { ProjectName = "Fun Boat" };
            var p2 = new Project() { ProjectName = "Jumbo Jet" };
            var p3 = new Project() { ProjectName = "Free Zoo" };
    
            var e1 = new Emp() { EmpName = "Wriju" };
            var e2 = new Emp() { EmpName = "Wrishika" };
            var e3 = new Emp() { EmpName = "Saswati" };
    
            p1.Emps.Add(e1);
            p1.Emps.Add(e2);
    
            p2.Emps.Add(e2);
            p2.Emps.Add(e3);
    
            p3.Emps.Add(e3);
            p3.Emps.Add(e1);
    
            using (var ctx = new EmpContext())
            {
                ctx.Projects.Add(p1);
                ctx.Projects.Add(p2);
                ctx.Projects.Add(p3);
                    
                ctx.SaveChanges();
            }
        }
    }

    Generated database would look like

    image

    Namoskar!!!

  • Wriju's BLOG

    CodeFirst EF 4.1 : Changing Database Table and Column name

    • 1 Comments

    At times we need to control the Table and Column name of our generated database or have different Entity/Property name of code than actual database in EF 4.1 Code First. There are two ways we can do it.

    Using Annotations

    using System.ComponentModel.DataAnnotations;
    
        //Changing database Table name to Employee
        [Table("Employee")]
        public class Emp
        {
            //Changing database column name to EmpId
            [Column("EmpId")]
            public int Id { get; set; }
            public string Name { get; set; }
        }

    Using FluentAPI

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        //Changing Database Column name to EmployeeId
        modelBuilder.Entity<Emp>()
            .Property(p => p.Id)
            .HasColumnName("EmployeeId");
    
        //Changing Database table name to EmployeeData
        modelBuilder.Entity<Emp>()
            .ToTable("EmployeeData");
    }
    Note: If you have both Annotation and FluentAPI available, the FluentAPI will win.

    Namoskar!!!

  • Wriju's BLOG

    Code First EF 4.1 : Missing “ADO.NET DbContext Generator” VS Template

    • 6 Comments

    I have seen people coming back to me asking questions about the template visible in Visual Studio 2010 as “ADO.NET DbContext Generator”. This template allows you to create the POCO classes and the context for CodeFirst from already existing edmx file.

    The template in Visual Studio looks like

    image

    But missing. But why?

    At times if you have used NuGet package manager to install the EF 4.1 then the ADO.NET DbContext Generator would not come.

    This template gets installed only when you install the complete EF 4.1 from MSDN here

    Namoskar!!!

  • Wriju's BLOG

    Code First 4.1 : Using Stored Procedure to Insert Data

    • 4 Comments

    Code First in Entity Framework does not support Stored Procedure by default. As there is no designer we cannot even map our stored procs to the entity. There are a many scenario we have seen where we are bound to use stored procedure for any database modifications (insert/update/delete). Here is how we can use stored procedure.

    image

    This would finally call the Stored Procedure.

    The stored proc used here is very simple

    ALTER PROCEDURE [dbo].[stp_InsertEmp]
    (
    	@Name as VARCHAR(50)
    ) AS
     
    	INSERT INTO Emps(Name) VALUES(@Name)

    Namoskar!!!

  • Wriju's BLOG

    LINQ to XML : Handling blank or no Element and Attribute

    • 7 Comments

    It quite so happen that you are working with XML where you are expecting a specific element in every set. But somehow that is missing in some of the sets.

    Now at runtime you would get an error..

    The XML file which I am targeting

    <?xml version="1.0" encoding="utf-8"?>
    <Employees>
      <Employee Location="Earth">
        <Name>Wriju</Name>
        <Email>a@a.com</Email>
      </Employee>
      <Employee Location="Moon">
        <Name>Tupur</Name>
        <Email>a@b.com</Email>
      </Employee>
      <Employee>
        <Name>Wrishika</Name>
      </Employee>  
    </Employees>

    Notice above the third element has missing Location attribute and Email element. So this would throw me a runtime error if I try to execute as below.

    var xml = XElement.Load(@"D:\Temp\Employee.xml");
    
    var q = from e in xml.Descendants("Employee")
            select new 
            {
                Name = e.Element("Name").Value,
                Location = e.Attribute("Location").Value,
                Email = e.Element("Email").Value
            };
    
    foreach (var k in q)
    {
        Console.WriteLine("Name : {0}, Email : {1}, Location : {2}", 
            k.Name, k.Email, k.Location);
    }

    Error would come for the 3rd element where both Location attribute and Email element are missing.

    Unhandled Exception: System.NullReferenceException: Object reference not set to an instance of an object

    Now what I need is simple. By using C# 3.0 extension method I can create two additional methods in a public static class as below

    //This method is to handle if element is missing
    public static string ElementValueNull(this XElement element)
    {
        if (element != null)
            return element.Value;
    
        return "";
    }
    
    //This method is to handle if attribute is missing
    public static string AttributeValueNull(this XElement element, string attributeName)
    {
        if (element == null)
            return "";
        else
        {
            XAttribute attr = element.Attribute(attributeName);
            return attr == null ? "" : attr.Value;
        }
    }
    

    Now my code would look like and would not throw any runtime error

    var xml = XElement.Load(@"D:\Temp\Employee.xml");
    
    var q = from e in xml.Descendants("Employee")
            select new 
            {
                Name = e.Element("Name").ElementValueNull(),
                Location = e.AttributeValueNull("Location"),
                Email = e.Element("Email").ElementValueNull()
            };
    
    foreach (var k in q)
    {
        Console.WriteLine("Name : {0}, Email : {1}, Location : {2}", 
            k.Name, k.Email, k.Location);
    }

    Namoskar!!!

  • Wriju's BLOG

    Windows Azure Storage Simplified

    • 0 Comments

    While working with Windows Azure it makes me feel as if I am working on ADO.NET Entity Framework and WCF Data Service. Everything is entity based and connection opens up through context.

    Lets see how can we create an application to add Movies to our database.

    Following are the using block entry

    image

    We need Movies entity

    image

    After that you need to choose the data source. In this case we are using development fabric. We can just change the values of the fabric to actual azure with 512 bit key and account name.

    image

    Now we need to initialize the RoleInstance to be able to read the config values

    image

    Hence after that initialize the CloudStorageAccount and CloudTableClient.

    image

    You may use the LINQ to read also with a combination of AsTableServiceQuery

    image

    That’s it!!!

    The complete code

    //Initializing Role of cloud project to be able to read the config
    CloudStorageAccount.SetConfigurationSettingPublisher((configName, configSetting) =>
    {
        configSetting(RoleEnvironment.GetConfigurationSettingValue(configName));
    });
    
    //Reading the connection from Config
    CloudStorageAccount sAcc;
    sAcc = CloudStorageAccount.FromConfigurationSetting("DataConnection");
    
    //Initializing the CloudTableClient
    CloudTableClient tableClient = new CloudTableClient(sAcc.TableEndpoint.AbsoluteUri, sAcc.Credentials);
    
    //Setting the table name 
    string tableName = "Movies";
    
    //Creating the table in storage 
    tableClient.CreateTableIfNotExist(tableName);
    
    //Initializung Context
    TableServiceContext context = tableClient.GetDataServiceContext();
    
    //Adding new entry
    context.AddObject(tableName,
        new Movies()
        {
            PartitionKey = "Action",
            RowKey = Guid.NewGuid().ToString(),
            Timestamp = DateTime.Now,
            Title = "Never Released..."
        });
    //Saving with retries 
    context.SaveChangesWithRetries();
    
    
    //Reading the values using LINQ
    var q = (from m in context.CreateQuery<Movies>(tableName)
                where m.PartitionKey == "Action"
                select m).AsTableServiceQuery<Movies>();
    
    dg.DataSource = q.ToList();
    dg.DataBind();

    Namoskar!!!

  • Wriju's BLOG

    MIX11 Recording Download using IE and Zune

    • 1 Comments

    Internet Explorer comes with a great RSS integration and by using that we can download the recording of MIX11.

    I have the channel9 MIX link http://channel9.msdn.com/Events/MIX/MIX11 and after I open it in IE you get to see the RSS

    image

    After that I choose the type of video I want to download and open Zune (installed locally).

    image

    Now you download as you want

    image

    Namoskar!!!

  • Wriju's BLOG

    EF 4.1 Code First Validation

    • 0 Comments

    When we either use the Fluent API or the attribute to put restrictions to our properties and while adding if we violet that, error would occur. Code First provides us set of classes to capture them

    Code First Model

    public class Department

    {

        [Key]

        public int DeptId { get; set; }

        public string DeptName { get; set; }

     

        public virtual ICollection<Employee> Employees { get; set; }

    }

     

    public class Employee

    {

        [Key]

        public int EmpId { get; set; }      

        [MaxLength(3)]

        public string EmpName { get; set; }

        public virtual Department Dept { get; set; }

    }

     

    public class EmpContext : DbContext

    {

        public DbSet<Department> Depts { get; set; }

        public DbSet<Employee> Emps { get; set; }

     

        protected override void OnModelCreating(DbModelBuilder modelBuilder)

        {

            modelBuilder.Entity<Department>().Property(p => p.DeptName).HasMaxLength(2);

        }

    }

    My Application Code (need to refer the namespace “System.Data.Entity.Validation)

    Database.SetInitializer<EmpContext>(new DropCreateDatabaseIfModelChanges<EmpContext>());

    using (var db = new EmpContext())

    {

        var d1 = new Department() { DeptName = "IT" };

        var d2 = new Department() { DeptName = "Software" };

     

        new List<Employee>

        {

            new Employee() { EmpName = "Wriju", Dept = d2 },

            new Employee() { EmpName = "Writam", Dept = d2 },

            new Employee() { EmpName = "Sumitra", Dept = d2 },

            new Employee() { EmpName = "Debajyoti", Dept = d2 }

        }.ForEach(e => db.Emps.Add(e));

     

        try

        {

            db.SaveChanges();

        }

        catch (DbEntityValidationException e)

        {

            foreach (var k in e.EntityValidationErrors)

            {

                foreach (var e1 in k.ValidationErrors)

                {

                    Console.WriteLine("{0} - {1}", e1.PropertyName, e1.ErrorMessage);

                }

            }

        }

    }

    Captured Errors

    EmpName - The field EmpName must be a string or array type with a maximum length of '3'.
    DeptName - The field DeptName must be a string or array type with a maximum length of '2'.
    EmpName - The field EmpName must be a string or array type with a maximum length of '3'.
    EmpName - The field EmpName must be a string or array type with a maximum length of '3'.
    EmpName - The field EmpName must be a string or array type with a maximum length of '3'.

    Namoskar!!!

  • Wriju's BLOG

    Using Code First through NuGet

    • 0 Comments

    While working for a Code First project u need to refer the assembly from already installed EF 4.1 update. Otherwise you can use NuGet to easily achieve it

    image

    After that you run the command Install-Package EntityFramework at the command window

    image

    Namoskar!!!

  • Wriju's BLOG

    ADO.NET Entity Framework Code First 4.1 - Online

    • 0 Comments

    April 20, 2011 at 11 AM Pacific Time.

    Please register at https://training.partner.microsoft.com/learning/app/management/LMS_ActDetails.aspx?UserMode=0&ActivityId=731858

    Learn what is new in ADO.NET Entity Framework Code First 4.1

    ADO.NET Entity Framework comes with a new update to make things simpler while accessing data.

    ·         Background - no edmx, no visual model

    ·         Assemblies

    ·         Create and Load Database

    ·         Data Annotations

    ·         DbContext, Database classes

    ·         Database Initializer

    ·         Fluent API

    ·         Configurable connection string

    Namoskar!!!

     

  • Wriju's BLOG

    EF 4.1 Code First - Running SQL Queries

    • 2 Comments

    ADO.NET Entity Framework’s Code First 4.1 allows us to execute SQL queries directly. You may need to get one column output or quickly update a table. One thing we need to be careful about running these raw queries is that you need to be double sure about the validity of these…

    If you are viewing this article and new to ADO.NET Entity Framework Code First then please visit my blog at http://blogs.msdn.com/b/wriju/archive/2011/04/10/ado-net-entity-framework-code-first-development.aspx

    Option 1 If I want to add values to my database,

    //Adding data through query
    var q1 = db.Database.ExecuteSqlCommand("INSERT INTO Departments(DeptName) Values('Test')");

    Option 2 Now want to read data store it already available entity. You need to call .ToList() to trigger the execution.

    //Reading data through query
    var q2 = db.Depts.SqlQuery("SELECT * FROM Departments").ToList();
    

    Option 3 Want to read data but do not have any entity.

    var q3 = db.Database.SqlQuery<string>("SELECT DeptName FROM Departments").ToList();
    

    Namoskar!!!

  • Wriju's BLOG

    EF Code First 4.1 Lazy Loading

    • 0 Comments

    EF Code First supports Lazy Loading as Model (edmx). You need to define the navigation properties to set the relationship to load the query.

    So if we try to implement the below code

       1:  public class Department
       2:  {
       3:      [Key] //To make it Primary Key and Identity
       4:      public int DeptId { get; set; }
       5:      public string DeptName { get; set; }
       6:   
       7:      //Create Employee navigation property for Lazy Loading (1:many)
       8:      public virtual ICollection<Employee> Employees { get; set; }
       9:  }
      10:   
      11:  /// <summary>
      12:  /// Employee class
      13:  /// </summary>
      14:  public class Employee
      15:  {
      16:      [Key] //To make it Primary Key and Identity
      17:      public int EmpId { get; set; }
      18:      public string FirstName { get; set; }
      19:      public string LastName { get; set; }
      20:      public int DeptId { get; set; }
      21:   
      22:      //Create Department navigation property for Lazy Loading
      23:      public virtual Department Department { get; set; }
      24:  }

    Hence the line 8 and 23 together with virtual would create the 1:many relationship.

    image

    After adding data if we try to write the below code it would Lazy Load the data

    using (var db = new EmpDeptContext())
    {
        var d = from dept in db.Depts
                select dept;
        foreach (var d1 in d)
        {
            Console.WriteLine("+++++++++++++");
            Console.WriteLine(d1.DeptName);
            Console.WriteLine("+++++++++++++");
    
            foreach (var e1 in d1.Employees)
            {
                Console.WriteLine(e1.FirstName + " " + e1.LastName);
            }
            Console.WriteLine("=============================");
        }
    }

    And by adding .Include we will get similar Immediate Loading.

    var d = from dept in db.Depts.Include("Employees")
            select dept;
    

    Namoskar!!!

  • Wriju's BLOG

    ADO.NET Entity Framework Code First Development

    • 3 Comments

    I liked LINQ to SQL for its clean approach of defining only code to be able to access the database. ADO.NET Entity Framework comes with a much more richer experience of you being the fine grained control over the code. In this current version we have Model First and Database First approaches, now we have Code First.

    You need to install the ADO.NET Entity Framework Code First API from Microsoft. I will let you Bing it. After that assume that you have two tables Department and Employee. One Department can have many employees.

    You need the EntityFramework assembly to be part of your reference. You also need ComponentModel.DataAnnotations. Your department and employee class would look like,

    using System.Data.Entity;
    using System.ComponentModel.DataAnnotations;
    
    /// <summary>
    /// Department class
    /// </summary>
    public class Department
    
    {
        [Key] //To make it Primary Key and Identity
        public int DeptId { get; set; }
        public string DeptName { get; set; }
    
        //Create Employee navigation property for Lazy Loading (1:many)
        public virtual ICollection<Employee> Employees { get; set; }
    }
    
    /// <summary>
    /// Employee class
    /// </summary>
    public class Employee
    {
        [Key] //To make it Primary Key and Identity
        public int EmpId { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public int DeptId { get; set; }
    
        //Create Department navigation property for Lazy Loading
        public virtual Department Department { get; set; }
    }
    

    After that you need the context class to create the connection

    public class EmpDeptContext : DbContext
    {
        public DbSet<Employee> Emps { get; set; }
        public DbSet<Department> Depts { get; set; }
    }
    

    After that you write your application to add Departments and Employees and this will automatically create a database first at you localhost\sqlexpress (if no option provided), then enter the data into it.

    var deptSoftware = new Department() { DeptName = "Software" };
    var deptIT = new Department() { DeptName = "IT" };
    
    using(var db = new EmpDeptContext())
    {
        new List<Employee> 
        {
            new Employee(){FirstName = "Wriju", LastName = "Ghosh", Department = deptSoftware},
            new Employee(){FirstName = "Saswati", LastName = "Sanyal", Department = deptSoftware},
            new Employee(){FirstName = "Wrishika", LastName = "Ghosh", Department = deptSoftware},
            new Employee(){FirstName = "Writam", LastName = "Ghosh", Department = deptIT},
            new Employee(){FirstName = "Debajyoti", LastName = "Ghosh", Department = deptIT},
            new Employee(){FirstName = "Sumitra", LastName = "Ghosh", Department = deptIT}
        }.ForEach(e => db.Emps.Add(e));
        int records = db.SaveChanges();
        Console.WriteLine("{0} record(s) saved", records);
    }

    That’s it!!! Isn’t it clean? No Edmx no extra resources.

    Namoskar!!!

  • Wriju's BLOG

    Moving On-premises SQL Server Database to SQL Azure

    • 0 Comments

    Is very easy and can’t think of anything simple. I did it with my favorite TestDB database Smile

    Open SQL Server Management Studio. Right click the database and select Generate Script

    image

    After that run the wizard as below

    image

     

    image

    Select “Script entire database and all database objects

    image

    Select “Save to new query window” and click advanced.

    image

    NoteChoose the property value of “Script for the database engine type” to “SQL Azure Database

    And also choose

    image

    Choose the property “Types of data to Script” to “Schema and data”. This would bring data along with the schema.

    image

    Now hit next and finish.

    Note: If you have any table which has no clustered index then you will not be able to import them to SQL Azure.

    Now you need to create a database at your SQL Azure (through Portal) and run the script from your SQL Management Studio. DoneSmile

    You could also use SSIS and BCP to do the same. But this one is the easiest to me.

    Namoskar!!!

  • Wriju's BLOG

    Channel 9 : TFS 2010 - First Look

    • 0 Comments

    Just published one Channel 9 video on TFS 2010 covering

     

    Ø  How to create Collection

    Ø  How to create Team Project

    Ø  How to setup the security

    Ø  How to create Workspace

    Ø  How to configure Source Control

    Ø  How to configure Team Build

    http://channel9.msdn.com/posts/TFS2010FirstLook

    Namoskar!!!

  • Wriju's BLOG

    TechEd 2011 India

    • 1 Comments

    Thanks everyone. It was pleasure talking to all of you in India TechEd 2011 on “Choosing Right Data Access Methodologies”. It was a jam packed session and a lot of people were standing or sitting on the stage. I loved talking. Huge!!!

    I have been getting emails to share resources. Let me tell you one thing. The slide and the recording will be available on TechEd 2011 India website. So keep watching.

    Here I will share the demo and the database script. I have uploaded them at http://bit.ly/g3OQpJ 

    Steps to follow,

    1. In your local SQL Server create a database TestDB .

    2 Run the script “01 TechEd2011_TestDB_Create and Insert.sql ” from share. This will create the tables and dummy value to it.

    3. Open the “DataAccess_Final.zip” file and change the connection strings in all .config files. Please feel free to comment here or send me email at wriju_ghosh@hotmail.com for any quick assistance.

    Blogs to follow

    ADO.NET Team blog http://blogs.msdn.com/b/adonet/

    WCF Data Services Team blog http://blogs.msdn.com/b/astoriateam/

    A big thank to everyone for coming in after heavy lunch and before the India world cup match. Amazing dedication and willingness to learn. Time was limited so was not able to show a many exciting things there. Keep watching my blog and I will keep things posted.

    Namoskar!!!

  • Wriju's BLOG

    TechEd 2011 India - Special

    • 5 Comments

    I have been following TechEds since 2005. This time India TechEd 2011 is very special to me. I am delivering session called

    Data Access Methodologies: When to choose what (ADO.NET, Entity Framework, LINQ, WCF Data Services) and the official abstract says,

    Often an Application requires to access database. A lot of evolving data access technologies are available today from Microsoft. Choose the right one for right type of your application (Windows Forms, Windows Presentation Foundation, ASP.NET, ASP.NET MVC, Silverlight etc). Find which one is the best fit for you from ADO.NET, LINQ, ADO.NET Entity Framework, and WCF Data Services. This session will also highlight on the future investments of data access technologies from Microsoft and help you decide the right one.

    With this I am very excited to talk about different data access technologies available today and what you need to know when to choose what. This talk will give you an idea about what is there in various different options we have today. We will focus on ADO.NET Entity Framework v4 and WCF Data Services. Hoping to make it a demo intensive talk - to me 1 hour is very less to cover this most debated area and moreover to a audience of experienced industry folks. 

    I need your best of luck for my session at TechEd 2011 - pray for the projector and demo to run smoothly as expected.

    Wish you to see there and connect personally.

    Namoskar!!!

  • Wriju's BLOG

    ADO.NET Entity Framework : Adding User Defined Function in Storage Model

    • 0 Comments

    Sometimes you may want to use same logic again and again. Let’s suppose you do not have access to your database which allows you to write function or stored proc. Never mind, EF allows you to define the logic at Model and you should be able to experience the same.

    You want to search an employee with its id. Open the edmx file in XML view and add the the below code under <schema>

    <Function Name="GetEmployeeFN" IsComposable="false">
      <CommandText>
        Select * from Emp WHERE EmpId = @id
      </CommandText>
      <Parameter Name="id" Type="int"></Parameter>
    </Function>
    
    And in the model browser you will find it just like when you import and SQL Stored Proc 
    
    image
    After that do a simple function import and get the power. 
    using (TestDBEntities db = new TestDBEntities())
    {
        foreach (var k in db.GetEmployeeFN(41))
        {
            Console.WriteLine(k.LastName);
        }
    
    Namoskar!!!
Page 8 of 25 (606 items) «678910»