Category Archives: Entity Framework

Model-First in the Entity Framework

So I finally had the situation come up to do a model-first approach to Entity Framework (EF).  It was shockingly simple.  Normally I design my databases first and go from there, this time I did my EF model.  Now this was just a simple four entity deal but I thought it would be a great Hello Model-First.

You simply create your entities in the designer, adding properties and adjusting their properties.  You know, like indicating someNum is an int32 instead of the default string, if something can be null, default values and so on.  You also add your associations.  Then you generate database from model.  I did this by right clicking the design surface and clicking on Generate Database from Model…   This will create a SQL script that you can run against your database.  In my case I did create an empty database with a SQL user before hand that I used in my connection information for generating the database.

If you still think it is harder than that, you can read this great article by Microsoft.  I wanted to look it up and make sure I did not leave something out and found that article.  I still suggest you look over the article.  It goes into much more detail than my short text, and they include screen shots.

One thing I did go back and do was change the name of that connection.  Visual Studio named it MyPartModelObjectContainer (or something close to that), where MyPart was basically what I named the Model.  This was simple to do as well.  You rename it int eh connectionString area of your web.config and in the properties of the model.edmx file.  You can see its properties by just clicking on the design surface, not an entity or anything, just on the empty space.

Entity Framework 4 Quickstart

Wanting to get started with Entity Framework 4?  Microsoft has a nice simple quickstart for it.  I am thinking of writing my won series of posts for using Entity Framework 4 for the practical developer.

http://msdn.microsoft.com/en-us/library/bb399182.aspx

Custom Validation with GridView and EF

This is to document how I do custom validation with a GridView in a website that uses Entity Framework.

Some assumptions:

  • I am using .NET4 with Entity Framework 4
  • I am using an EntityDataSource object
  • My GridView command buttons are templates and have the ID set as a command argument

In this example I will address doing an update from a GridView where we want to make sure a field called someName is unique. The table in question has an identity field that is unique and is called ID. Our model is MyModel and our entity is named MyEntities.

The first thing we need to do is create an OnRowCommand event for our GridView. This event will store the ID of the row we want to update. We will store this in the ViewState. My OnRowCommand event consists of a switch statement which I will put below.

        switch (e.CommandName)
        {
            case "Edit":
                ViewState["editID"] = e.CommandArgument.ToString();
                break;
            case "Update":
                ViewState["editID"] = e.CommandArgument.ToString();
                break;
            case "Cancel":
                ViewState["editID"] = null;
                break;
            default:
                break;
        }

The next important step is the OnServerValidate event for our custom validation control. This is where the real work happens. My OnServerValidate event puts the value into a string, and the ID into an int. It then calls another private method to set the e.isValid property to the results of the private method. The private method takes the value and ID as parameters. The check is really just counting the number of occurrences of the value in the table that does not equal the ID. Of course in your situation you may not have a string as a value, but you get the idea.

    protected void CV_UpdateUniqueName(object sender, ServerValidateEventArgs e)
    {
        string sName = e.Value;
        int nID = Convert.ToInt32(ViewState["editID"].ToString());
        e.IsValid = IsNameUnique(sName, nID);
    }

    private bool IsNameUnique(string sName, int nID)
    {
        bool isUnique = false;
        try
        {
            using (MyEntities oEntities = new MyEntities())
            {
                int nMatches = (from a in oEntities.tblMyTable where a.someName == sName && a.id != nID select a).Count();
                isUnique = (nMatches <= 0);
            }
        }
        catch (Exception e)
        {
            //Error handling here
        }
        return isUnique;
    }

There you have it, pretty simple.

An Update 6/2/2011
Thinking about it now, perhaps using control state would be better than view state, at least if you tend to turn off view state.