Home > Uncategorized > Entity framework–code first

Entity framework–code first

It is darn simple and straight forward to get started using entity framework code first. Lessons learned from ef code first tutorial.

  1. Create a new C# project in visual studio 2010
  2. If you do not have nuget, use tools –> extension manager to install it
  3. Use nuget to setup your project for entity framework; install-package entityframework
  4. Add a connection string in app.config
  5. Code something like below

class Person

{

    public int PersonId { get; set; }

    public string Name { get; set; }

    public int Age { get; set; }

}

 

class MyContext : DbContext

{

    public DbSet<Person> Persons { get; set; }

}

 

class Program

{

    static void Main(string[] args)

    {

        Database.SetInitializer<MyContext>(

            new DropCreateDatabaseIfModelChanges<MyContext>());

 

        using (var ctx = new MyContext())

        {

            ctx.Persons.Add(new Person { Name = "Olle" + Guid.NewGuid(), Age = 23 });

            ctx.Persons.Add(new Person { Name = "Pelle" + Guid.NewGuid(), Age = 54 });

            ctx.Persons.Add(new Person { Name = "Sven" + Guid.NewGuid(), Age = 36 });

            int x = ctx.SaveChanges();

            Console.WriteLine("{0}", x);

 

            var persons = from p in ctx.Persons where p.Age > 25 select p;

            foreach (var p in persons)

            {

                Console.WriteLine(p.PersonId + " " + p.Name);

            }

        }

    }

}

Advertisements
Categories: Uncategorized
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: