Entity Framework Step By Step 3 – Model First

As I have discussed in my previous post we know how to create a Database using Entity Framework Model First framework. In this post we’ll see how to read & write data using EF.

When you create the Database using the designer, entity classes which we can use to access the data will be automatically generated in your solution. Please see the highlighted classes in the screen shot below.

image

  • BloggingModel.Context.cs :- 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.
  • Blog.cs & Post.cs :- Entity classes with properties defined in the database table.
Writing Data

static void WriteData()
      {

          using (var db = new BloggingContext())
          {
              // Create and save a new Blog
              Console.Write("Enter a name for a new Blog: ");
              var name = Console.ReadLine();

              var blog = new Blog { Name = name };
              db.Blogs.Add(blog);
              db.SaveChanges();

              ReadData();
          }
      }

Reading Data

static void ReadData()
{

    using (var db = new BloggingContext())
    {
        var query = from b in db.Blogs
                    orderby b.Name
                    select b;

        foreach (var item in query)
        {
            Console.WriteLine(item.Name);
        }

    }
}

Making Changes To Model

if you want to make any changes to your model the follow the following steps.

  1. Go to the designer & make the changes you want.
  2. Right click on the design surface & select “Generate Database from Model
  3. You may receive warnings about overwriting the existing DDL script and the mapping and storage parts of the model, click Yes for both these warnings
  4. Execute the updated SQL statement.

Comments

Popular posts from this blog

Responsive Web Design

Contract First Development in WCF 4.5

Affine Cipher in C#