Entity Framework Code First Approach New
Entity Framework Code First Approach New
Code First modeling workflow targets a database that doesn’t exist and Code
First will create it.
It can also be used if you have an empty database and then Code First will
add new tables to it.
Code First allows you to define your model using C# or VB.Net classes.
Additional configuration can optionally be performed using attributes on your
classes and properties or by using a fluent API.
Class1
public class Student {
public int ID { get; set; }
public string LastName { get; set; }
public string FirstMidName { get; set; }
public DateTime EnrollmentDate { get; set; }
Class2
Class3
add some data and then retrieve it. Following is the code in main method.
static void Main(string[] args) {
context.Students.Add(student);
context.Students.Add(student1);
context.SaveChanges();
You can define the base constructor of the context class in the following ways.
No Parameter
Database Name
Connection String Name
If you specify the base constructor of the context class without any parameter as shown in
the above example, then entity framework will create a database in your local
SQLEXPRESS server with a name {Namespace}.{Context class name}.
Database Name
If you pass the database name as a parameter in a base constructor of the context class,
then Code First will create a database automatically again, but this time the name will be the
one passed as parameter in the base constructor on the local SQLEXPRESS database
server.
If the name of the connection string matches the name of your context (either
with or without namespace qualification), then it will be found by DbContext
when the parameter less constructor is used.
If the connection string name is different from the name of your context, then
you can tell DbContext to use this connection in Code First mode by passing
the connection string name to the DbContext constructor.
public class MyContext : DbContext {
public MyContext() : base("name = MyContextDB") {}
public virtual DbSet<Course> Courses { get; set; }
public virtual DbSet<Enrollment> Enrollments { get; set; }
public virtual DbSet<Student> Students { get; set; }
}
<connectionStrings>
<add name = "MyContextDB"
connectionString = "Data Source =.;Initial Catalog = EFMyContextDB;Integrated Security =
true"
providerName = "System.Data.SqlClient"/>
</connectionStrings>