This is continution part to Code First Approcach startUp with MVC
Let's assume that we want to create a simple application for Banking Apllication. Admin of this Banking application should be able to add or update User, add account and add money. Instead of designing database tables first, let's start creating classes for our Banking domain, as and when needed. First, we will create two simple User and Account classes where every User is associated with one Account as shown below.
Right Click on Model folder and add new Class
User Class Defination
public class User
{
public User()
{
}
public int UserID { get; set; }
public string UserName { get; set; }
public DateTime DateOfBirth { get; set; }
public byte[] Photo { get; set; }
public int Age { get; set; }
public Account account { get; set; }
public DateTime CreatedDate { get; set; }
}
Account Definition
public class Account
{
public int AccountId { get; set; }
public float Balance { get; set; }
}
Now, we are done with the initial domain classes for our Banking application. Code-First approach also requires context class which should be derived from DbContext
Create a context class as shown below, which derives from DBContext class and exposes DbSet properties for the types that you want to be part of the model, e.g. User and Account class, in this case. DbSet is a collection of entity classes (aka entity set), so we have given property name as plural of entity name like Users and Accounts .
If you are going to paste this code as such then you have to add new namespace that give you the access to class DbContext .
using System.Data.Entity;
Now, we are done with the required classes for the code-first approach. We will now add Banking application using context class
public class AccountContext : DbContext
{
public AccountContext() : base()
{
}
public DbSet<User> Users { get; set; }
public DbSet<Account> Accounts { get; set; }
}
Now Front View.
Right Click on the Controller folder and select folder.
Note: if you don't get model class, rebuild and try again.
Click add and you are done.
Every thing is ok. not event single code to write and you are done with CRUD operation in Mvc with entityFramework.
Last Thing you Have to do is add connection string if you are not using express version with default instance name
if you following along me article, then first you get this page with big server error ,
just add /Users to existing Url and hit error.
For any error come to feel free to drop message at @RakeshYadvanshi
Download Code here
Post a Comment