Great/Terrible Ideas

  • ask me anything
  • rss
  • archive
  • EntityFramework CodeFirst is awesome for database crap

    I’m not usually a fan of Microsoft Magic, but the code first features of entity framework are super easy to use and understand.

    If you write any object oriented programs that talk to a database, you know that talking to the database can be a lot of tedious and uninteresting code to write, especially if your database is simple.

    First, download the entityFramework nuget package with the nuget package manager.

    Let’s say you had a class like this:

    public class UserPref
    {
        public string UserName { get; set; }
        public string Key { get; set; }
        public string Payload { get; set; }
    }
    

    Just add a primary key

    public class UserPref
    {
        [Key]
        public int Id { get; set; }
        public string UserName { get; set; }
        public string Key { get; set; }
        public string Payload { get; set; }
    }
    

    And make a class that inherits DbContext and add a property of type DbSet<UserPref> to it to make it a table. The next time the application starts, it will connect to the database with the default connection string in the app.config file and just create a database.

    Don’t like making migrations? Type enable-migrations -enableautomaticmigrations in the package manager command prompt. That’s really it. Way to go microsoft magic.

    Source: msdn.microsoft.com
    • November 1, 2012 (12:30 am)
    • 1 notes
    • #code
    • #csharp
    • #EntityFramework
    • #database
    • #code first
    1. saveroom4pie likes this
    2. poptart911 posted this
© 2012–2013 Great/Terrible Ideas