Pages

Showing posts with label DbSet. Show all posts
Showing posts with label DbSet. Show all posts

Tuesday, May 6, 2014

Migration: Helpful When Seeding Database and Error is Thrown

Using Entity Framework Migration, I was seeding a database.

From the Package Manager Console window and after entering Update-Database, an error was displayed.

Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.

This was the only information about error, and the error message didn’t indicate any good advise what caused the error.

Shown below is a work-around found at StackOverflow, which helped pin point the error.

Stackoverflow Overridding SaveChanges

public partial class Database : DbContext
{
public override int SaveChanges()
{
try
{
return base.SaveChanges();
}
catch (DbEntityValidationException ex)
{
var sb = new StringBuilder();

foreach (var failure in ex.EntityValidationErrors)
{
sb.AppendFormat("{0} failed validation\n", failure.Entry.Entity.GetType());
foreach (var error in failure.ValidationErrors)
{
sb.AppendFormat("- {0} : {1}", error.PropertyName, error.ErrorMessage);
sb.AppendLine();
}
}

throw new DbEntityValidationException(
"Entity Validation Failed - errors follow:\n" +
sb.ToString(), ex
); // Add the original exception as the innerException
}
}
}



This post is for the purpose of my notes only.
“I invented nothing new. I simply assembled the discoveries of other men behind whom were centuries of work. Had I worked fifty or ten or even five years before, I would have failed. So it is with every new thing. Progress happens when all the factors that make for it are ready and then it is inevitable. To teach that a comparatively few men are responsible for the greatest forward steps of mankind is the worst sort of nonsense.”



Henry Ford

Saturday, August 18, 2012

Code-First: From UML Class Diagram to Creating MS SQL Database

Over the years designing web applications, I have sketched thoughts onto paper; sketching out c# classes and database table relations. I knew there were great modeling programs to assist me, but I never bothered researching. I didn’t want to learn another language or program.

However, recently I learned of .Net 4.0+ EntityFramework and UML Modeling. These two allow me to create POCO classes, DB tables, and relationships between DB tables.
It is very straight forward, which I show the process I followed below:

My Sloution Explorer shows 4 projects:

DataLayer: a C# class project exposing a DbContext layer.

Model: a UML class diagram is created and C# classes are generated from its packages .
ModelLib: where the C# classes are stored after being generating.

WebApplication1: allows to initiate the Context and possibility create database.




First, Within a black .Net 4.0 solution, I Created a new Modeling Project, I dragged out an UML class diagram and made associations:


After creating class diagram, I right clicked on each package and selected Generate Code:



Clicking Generate Code a new C# class project is created and all modeled classes from the Class Diagram classes are created and saved within a specified folder.
  • The folder’s name, where the derived classes are saved, is derived from their package’s name.
  • The project’s name takes the model project’s name and apppends “Lib”

Second, I created a C# class project with only one C# class, which I named: Context.cs. This class is the context layer and will inherit from DbContext.

From MSN (MSDN DbContext):

DbContext Class

Entity Framework 5.0 Represents a combination of the Unit-Of-Work and Repository patterns and enables you to query a database and group together changes that will then be written back to the store as a unit. DbContext is conceptually similar to ObjectContext.

DbSet<TEntity> Class

Represents a typed entity set that is used to perform create, read, update, and delete operations. DbSet is not publicly constructible and can only be created from a DbContext instance.


Lastly, I created a Web Application, and in the code behind initiated the Context class. Because of lazy loading, if I was to only initiate the Context class, no DB tables would be created. Therefore, I selected something from the Client table and converted to a List. By converted it to a list, it must make a round trip to the database, and therefore the database tables will be created.
Special Note: Reference:
  • EntityFramework
  • System.Data.Entity
  • Context namespace (dogPedalerEnityMSSQL)
This name was chosen because Entity Framework will name the database after the Context’s Namespace. If no Connection String is found in the web.config, then Entity Framework will create SQLExpress Database named dogPedalerEnityMSSQL.Context (Namespace.Class).

Complete, I found this to be great. Going from Model to Classes to Creating DB tables.
This is only for my notes, and additionally it would be great, if someone receives benefit from my notes.