What is Entity framework !?

Getting started with Entity Framework

 What is Entity framework !?

MSDN answers to this question :"Entity Framework is an Object Relational Mapper (ORM). It basically generates business objects and entities according to the database tables provides ability to do CRUD operations , relations and etc."

And also about wikipedia's definition : "The Entity Framework is a set of technologies in ADO.NET that support the development of data-oriented software applications. Architects and developers of data-oriented applications have struggled with the need to achieve two very different objectives. They must model the entities, relationships, and logic of the business problems they are solving, and they must also work with the data engines used to store and retrieve the data. The data may span multiple storage systems, each with its own protocols; even applications that work with a single storage system must balance the requirements of the storage system against the requirements of writing efficient and maintainable application code. The Entity Framework enables developers to work with data in the form of domain-specific objects and properties, such as customers and customer addresses, without having to concern themselves with the underlying database tables and columns where this data is stored. With the Entity Framework, developers can work at a higher level of abstraction when they deal with data, and can create and maintain data-oriented applications with less code than in traditional applications. Because the Entity Framework is a component of the .NET Framework, Entity Framework applications can run on any computer on which the .NET Framework starting with version 3.5 SP1 is installed."

 

Forget about definitions and just Make your hands dirty to learn!

I just Use the code first feature of entity framework , it means  creating our model and then creating  database based on Model , in other words you can use C# or VB class to generate database , and also you can map your model to an existing database (if your database has been designed earlier).

there are lots of reason why I'm interested in to use Code first .in entity framework you can customize persistence easily , it is better when you are going to write Unit test , and more about persistence of Ignorance (I'm not going to talk about this one in current article)

Note :You can use code first feature via at least version 4.1 or later .

I'm using Asp.net MVC in this article ,Create a class with this definition :

  1.     public class Account
  2.      {
  3.         public int Id { get; set; }
  4.         public string Name { get; set; }
  5.         public decimal Balance { get; set; }
  6.       }

Now create your context class:

  1.  public class ContextClass : DbContext
  2.     {
  3.        public ContextClass(string connectionString) :base(connectionString)
  4.         {
  5.         }
  6.        public DbSet<Account> Accounts { get; set; }
  7.     }

And in Web.config  :

  1. <connectionStrings>
  2.     <add name="ContextClass" connectionString="Data Source=EHSAN-PC;Initial Catalog=BlogArticle;Integrated Security=SSPI" providerName="System.Data.SqlClient" />
  3.  </connectionStrings>

Now create a simple controller to calling the context class to finalize the creating the database in your management studio

  1.     public class EntityFrameworkController : Controller
  2.     {
  3.         private ContextClass _contextClass;
  4.  
  5.         public EntityFrameworkController()
  6.         {
  7.             _contextClass = new ContextClass();
  8.         }
  9.       
  10.         public ActionResult Index()
  11.         {
  12.             Account account= _contextClass.Accounts.First();
  13.             return View(account);
  14.         }     
  15.     }

Just run the project and request this Index action In Url , you can also create some fake data by hard coding in the action .If you go to sql management studio , you have created the BlogArticle database successfully !So ,database tables  built by DbContext based on model properties by running the project , now if we make any change in our domain model , databebase tables and our model won't be compatible , to solve this , change  your ContextClass like this :

  1.     public class ContextClass : DbContext
  2.     {
  3.         public ContextClass()
  4.         {
  5.             if (this.Database.Exists() && !this.Database.CompatibleWithModel(false))
  6.                 this.Database.Delete();
  7.             if (!this.Database.Exists()) this.Database.Create();
  8.         }
  9.         protected override void OnModelCreating(DbModelBuilder modelBuilder)
  10.         {
  11.             base.OnModelCreating(modelBuilder);
  12.         }
  13.         public DbSet<Account> Accounts { get; set; }

Initializing the database :

Entity framework provides to initialize data base with fake data , to do this add a new class to project with this definition:

  1.     public class InitializerClass :DropCreateDatabaseIfModelChanges<ContextClass>
  2.     {
  3.         protected override void Seed(ContextClass context)
  4.         {
  5.             new List<Account>
  6.                 {
  7.                     new Account {Id = 1, Balance = 34523, Name = "Mark"}
  8.                 };
  9.             base.Seed(context);
  10.         }
  11.     }

And also you  have to add this in global.asax

  1.         protected void Application_Start()
  2.         {
  3.             AreaRegistration.RegisterAllAreas();
  4.  
  5.             Database.SetInitializer(new InitializerClass());
  6.  
  7.          }

Fluent Configuration

you can define any kind of database field by EF built in mapping feature , for example about mapping the account 

  1.  public class AccountMapping : EntityTypeConfiguration<Account>
  2.     {
  3.         public AccountMapping()
  4.         {
  5.             this.ToTable("Account");
  6.             this.HasKey(a => a.Id);
  7.             this.Property(a => a.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
  8.             this.Property(a => a.Name).IsOptional();
  9.             this.Property(a => a.Balance).IsRequired();
  10.          }
  11.     }

 and then you have to add this line of code to your context class in OnModelCreating

  1.   modelBuilder.Configurations.Add(new AccountMapping());

 

RelationShips in EF  

You can define one-to-one , one-to-many , many-to-one and many-to-many mapping  by entity framework , lets implement them.Add a new class to your Model

  1.  public class AccountOwner
  2.     {
  3.         public int Id { get; set; }
  4.         public string Name { get; set; }
  5.         public string  Email { get; set; }
  6.         public virtual Account Account { get; set; }
  7.     }

And change the Account class like this :

  1.  public class Account
  2.     {
  3.         public int Id { get; set; }
  4.         public string Name { get; set; }
  5.         public decimal Balance { get; set; }
  6.         public virtual AccountOwner AccountOwner { get; set; }
  7.     }

And Change the mapping class of Account like this :

  1.  public class AccountMapping : EntityTypeConfiguration<Account>
  2.     {
  3.         public AccountMapping()
  4.         {
  5.             this.ToTable("Account");
  6.             this.HasKey(a => a.Id);
  7.             this.Property(a => a.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
  8.             this.Property(a => a.Name).IsOptional();
  9.             this.Property(a => a.Balance).IsRequired();
  10.             this.HasRequired(a=>a.AccountOwner).WithOptional().WillCascadeOnDelete();
  11.         }
  12.     }

And about mapping class of AccountOwner :

  1.  public class AccountOwnerMapping : EntityTypeConfiguration<AccountOwner>
  2.     {
  3.         public AccountOwnerMapping()
  4.         {
  5.             this.ToTable("AccountOwner");
  6.             this.HasKey(a => a.Id);
  7.             this.Property(a => a.Id).HasColumnName("AccountOwnerId").HasDatabaseGeneratedOption(
  8.                 DatabaseGeneratedOption.Identity);
  9.             this.Property(a => a.Email).HasMaxLength(100).IsRequired();
  10.         }
  11.     }

 and in Order to have your mapping class influence in database you should change the ContextClass :

  1.  public class ContextClass : DbContext
  2.     {
  3.         public ContextClass()
  4.         {
  5.             if (this.Database.Exists() && !this.Database.CompatibleWithModel(false))
  6.                 this.Database.Delete();
  7.             if (!this.Database.Exists()) this.Database.Create();
  8.         }
  9.         protected override void OnModelCreating(DbModelBuilder modelBuilder)
  10.         {
  11.             base.OnModelCreating(modelBuilder);
  12.  
  13.             modelBuilder.Configurations.Add(new AccountMapping());
  14.             modelBuilder.Configurations.Add(new AccountOwnerMapping());
  15.         }
  16.  
  17.         public DbSet<Account> Accounts { get; set; }
  18.         public DbSet<AccountOwner> AccountOwners { get; set; }

one-to-many 

create these classes 

  1.  public class Blog
  2.     {
  3.         public int Id { get; set; }
  4.         public String Title { get; set; }
  5.         public string Text { get; set; }
  6.         public virtual  ICollection<Category> Categories { get; set; }
  7.     }
  8.  
  9.  public class Category
  10.     {
  11.        public int Id { get; set; }
  12.        public string Name { get; set; }
  13.        public virtual Blog Blog { get; set; }
  14.     }

Now Add two Mapping class for this Models:

  1.  public class CategoryMapping :EntityTypeConfiguration<Category>
  2.     {
  3.         public CategoryMapping()
  4.         {
  5.             this.ToTable("Category");
  6.             this.HasKey(c => c.Id);
  7.             this.Property(c => c.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
  8.             this.Property(c => c.Name);
  9.         }
  10.     }
  11.  
  12.   public class BlogMapping : EntityTypeConfiguration<Blog>
  13.     {
  14.         public BlogMapping()
  15.         {
  16.             this.ToTable("Blog");
  17.             this.HasKey(b => b.Id);
  18.             this.Property(b => b.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
  19.             this.Property(b => b.Title).IsRequired();
  20.             this.Property(b => b.Text).HasColumnType("text").IsMaxLength().IsOptional().HasColumnName("Text");
  21.             this.HasMany(b=>b.Categories).WithRequired(b=>b.Blog).WillCascadeOnDelete();
  22.         }
  23.     }

And just like one to one sample add the blog and category configurations to Context class

  1.     public class ContextClass : DbContext
  2.     {
  3.         public ContextClass()
  4.         {
  5.             if (this.Database.Exists() && !this.Database.CompatibleWithModel(false))
  6.                 this.Database.Delete();
  7.             if (!this.Database.Exists()) this.Database.Create();
  8.         }
  9.         protected override void OnModelCreating(DbModelBuilder modelBuilder)
  10.         {
  11.             base.OnModelCreating(modelBuilder);
  12.  
  13.             modelBuilder.Configurations.Add(new AccountMapping());
  14.             modelBuilder.Configurations.Add(new AccountOwnerMapping());
  15.             modelBuilder.Configurations.Add(new CategoryMapping());
  16.             modelBuilder.Configurations.Add(new BLogMapping());
  17.         }
  18.         public DbSet<Account> Accounts { get; set; }
  19.         public DbSet<AccountOwner> AccountOwners { get; set; }
  20.         public DbSet<Blog> Blogs { get; set; }
  21.         public DbSet<Category> Categories { get; set; }
  22.    }

About many to many , create Product class with this definition

  1.     public class Product
  2.     {
  3.         public int Id { get; set; }
  4.         public string ProductName { get; set; }
  5.         public decimal Amount { get; set; }
  6.     }

And Customer class :

  1.   public class Customer
  2.     {
  3.         public int Id { get; set; }
  4.         public string CustomerName { get; set; }
  5.     }

And finally ProductCustomer :

  1.  public class ProductCustomer
  2.     {
  3.         public virtual Product ProductId { get; set; }
  4.         public virtual Customer CustomerId { get; set; }
  5.     }

I thinks You know how to map Product and Customer , Don’t you !?

you could also remove the ProductCustomer Class and change the Customer and Product class to achieve the many to many mapping 

  1. public class Customer
  2.     public int Id { get; set; }
  3.     public string CustomerName { get; set; }
  4.     public virtual List<Product> Products {get; set;}
  5.  }
  6.  
  7.  public class Product
  8.  {
  9.     public int Id { get; set; }
  10.     public string ProductName { get; set; }
  11.     public decimal Amount { get; set; }
  12.     public virtual List<Customer> Customers {get;set;}
  13.  }
  14.  

 happy coding!


Tags: Entity Framework


comments powered by Disqus