Introduction
This tip is about how to connect with an existing table in the database.
Background
For learning Code First, you can refer to the following:
Using the Code
The database name is MyClass
and it consists of only one table "ClassAll
".
Below is ClassAll
class with the same attributes and properties as of the table .
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace School.Data.Model
{
public partial class ClassAll
{
public int SchoolRollNo { get; set; }
public int Standard { get; set; }
public int ClassRollNo { get; set; }
public string Name { get; set; }
public string Gender { get; set; }
public int Percentage { get; set; }
public System.DateTime Date { get; set; }
}
}
The class ClassAllMap
is used to map with the existing table in the database.
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.ModelConfiguration;
namespace School.Data.Model.Mapping
{
public class ClassAllMap : EntityTypeConfiguration<ClassAll>
{
public ClassAllMap()
{
this.HasKey(t => t.SchoolRollNo);
this.Property(t => t.SchoolRollNo)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
this.Property(t => t.Name)
.IsRequired()
.HasMaxLength(50);
this.Property(t => t.Gender)
.IsRequired()
.IsFixedLength()
.HasMaxLength(10);
this.ToTable("ClassAll");
this.Property(t => t.SchoolRollNo).HasColumnName("SchoolRollNo");
this.Property(t => t.Standard).HasColumnName("Standard");
this.Property(t => t.ClassRollNo).HasColumnName("ClassRollNo");
this.Property(t => t.Name).HasColumnName("Name");
this.Property(t => t.Gender).HasColumnName("Gender");
this.Property(t => t.Percentage).HasColumnName("Percentage");
this.Property(t => t.Date).HasColumnName("Date");
}
}
}
MyClassContext
is the reference to the "MySchool
" database. In this code, we are using the ClassAllMap
declared above for configuration.
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using School.Data.Model.Mapping;
namespace School.Data.Model
{
public partial class MyClassContext : DbContext
{
static MyClassContext()
{
Database.SetInitializer<MyClassContext>(null);
}
public MyClassContext()
: base("Name=MyClassContext")
{
}
public DbSet<ClassAll> ClassAlls { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new ClassAllMap());
}
}
}
If using SQL Server Express Edition, in web.config file, add the connection string as follows:
<connectionStrings>
<add name="MyClassContext" providerName="System.Data.SqlClient"
connectionString="Server=.\SQLEXPRESS;Database=MyClass;Trusted_Connection=true;" />
</connectionStrings>