Introduction
In this blog we will see how to access sql server database with entity framework code first approach and later we will also look at how we can perform select data operation using complex type.
Step 1: Create asp.net web application

Employee.cs
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- namespace ComplexType_CFA_SelectApp
- {
- public class Employee
- {
- public Employee()
- {
- }
- public int Id { get; set; }
- public string FirstName { get; set; }
- public string LastName { get; set; }
- public EmployeeDetails EmployeeDetails { get; set; }
- }
- }
EmployeeDetails.cs
- using System;
- using System.Collections.Generic;
- using System.ComponentModel.DataAnnotations.Schema;
- using System.Linq;
- using System.Web;
- namespace ComplexType_CFA_SelectApp
- {
- [ComplexType]
- public class EmployeeDetails
- {
- public EmployeeDetails()
- {
- }
- public int Phone { get; set; }
- public int Age { get; set; }
- public string Email { get; set; }
- }
- }
Employeecontext.cs
- using System;
- using System.Collections.Generic;
- using System.Data.Entity;
- using System.Linq;
- using System.Web;
- namespace ComplexType_CFA_SelectApp
- {
- public class EmployeeContext: DbContext
- {
- public EmployeeContext()
- : base("EmployeeConn")
- {
- Database.SetInitializer<EmployeeContext>(new CreateDatabaseIfNotExists<EmployeeContext>());
- }
- protected override void OnModelCreating(DbModelBuilder modelBuilder)
- {
- //Set primary key to Employee table
- modelBuilder.Entity<Employee>().HasKey(m => m.Id).Property(m => m.Id).IsRequired();
- //First Name is required and Max Length is 50
- modelBuilder.Entity<Employee>().Property(p => p.FirstName).IsRequired().HasMaxLength(50);
- //Last Name is required and Max Length is 50
- modelBuilder.Entity<Employee>().Property(p => p.LastName).IsRequired().HasMaxLength(50);
- //Age is required
- modelBuilder.ComplexType<EmployeeDetails>().Property(p => p.Age).IsRequired();
- //Phone is required
- modelBuilder.ComplexType<EmployeeDetails>().Property(p => p.Phone).IsRequired();
- //Email is required
- modelBuilder.ComplexType<EmployeeDetails>().Property(p => p.Email).IsRequired();
- }
- public DbSet<Employee> Employees { get; set; }
- }
- }


Join the conversation! Your thoughts help the community grow.