Code-first in Entity Framework

    Into

    Under .NET, there are two native ORMs developed and maintained by Microsoft, the Entity Framework and Linq2Sql. However, the Entity Framework continues to grow at an impressive pace, and nothing really is known about the future of Linq2Sql.

    Entity Framework offers a convenient designer, a huge number of mapping options, auto-generation of model classes, but there is a fat minus for all this - giant and bloated generated classes, which can also not be changed manually - because every time you change the model in the designer, everything will be recreated anew . Compare this with pure classes and attributes added to them, as in Linq2Sql, and you will understand why so many people claim the lightness of Linq2Sql and the monstrosity of EF.

    Of course, every problem has a solution, and this is no exception. Partial classes will allow you to add the necessary functionality, and specially created classes with validation rules marked with the [MetadataType] attribute will make it possible to use validation attributes for model classes. But together it doesn’t turn out very beautifully - the classes spread over the project, the increase in their number, and all the same complexity in support.

    Do not forget about the working conditions of model classes: they must either inherit from EntityObject or implement the EntityWithKey, IEntityWithChangeTracker and IEntityWithRelationships interfaces.

    So what should we do for those who want to get the simplest classes for working inside ORM?

    ROSO and Code-First

    For the first time, support for ROSO (Plain Old CLR Objects), i.e. working with simple classes, as with models, appeared in EF 4.

    Note

    Despite the declared support in Visual Studio SP1, I still had to install Visual Studio Tools for SQL Server Compact 4 and EF Code First Package for correct operation.

    For example, here is such a class
    public class Author
            {
                public int AuthorID { get; set; }
                public string Email { get; set; }
                public string Name { get; set; }
            }
    

    Describes the fully functional entity "author", and he does not need any base class, nor interfaces, nor attributes or metadata.

    The simplest entry point will look like this:
    public class Library : DbContext
            {
                public DbSet Authors { get; set; }
            }

    And that’s all! Immediately after creating the Library object, you can work with it using all the advantages of EF.

    Code-First is a new feature alongside Model-First and Database-First. Now you can first write code describing the model classes, and then the framework will automatically create a database using this code.
    The best part is that the types of relations will be recognized - it is enough to simply define object references for 1: 1, ICollection for a 1: n relationship, and reciprocal ICollection for m: n. In this case, the staging table will also be created automatically. To provide a lazy load, the virtual keyword is enough in the property definition.

    Attributes from the namespace are also fully supported. System.ComponentModel.DataAnnotations

    The main ones are:
    • [Key] - indicates that this property will be the key.
    • [NotMapped] - do not display the property on columns in the database.
    • [Column (“columnName”, TypeName = ”typeName”] - indicates the column in the database on which the field and its type are displayed. It is useful when the class has a property of type byte [] that stores, for example, a picture, and in the database it will be displayed on special type of image.
    UPD However, you cannot specify a subset of the type in this way: for example, for strings, the type nvarchar (MAX) is selected in the database by default and this attribute cannot explicitly specify the field length nvarchar (30)
    • [MinLength], [MaxLength], [ Required] and others to provide data verification,

    Code-First is designed to work with the new version of SQL Server CE 4.0. lucine in MVC3, and some people alreadytranslate sites to work with such a database, and not standard SQL Express.

    By default, the database generator tries to create a SQL Express database, if it fails, then SQL Server CE. This behavior is easily overridden in app.config

    Note that the name of the connection string must match the name of the access point class (DbContext).

    You can also define a strategy for creating a database (primary generation or update). Every strategy is a class that implements the IDatabaseInitializer interface, i.e. You can determine your strategy, entering any data into the database during the period of active development of the program.
    The predefined strategies are CreateDatabaseIfNotExists (create a database if it does not exist), DropCreateDatabaseAlways (the database will always be deleted and recreated), DropCreateDatabaseIfModelChanges (it is recreated when the model changes)

    The database strategy is changed by calling
    Database.SetInitializer (new DropCreateDatabaseAlways;

    When creating a database, the framework creates another service table, EdmMetadata, which stores the hash of the model at the time of creation. This is inconvenient when actively developing the database and classes, but there is a solution - overloading the OnModelCreating method of the DbContext class.
                protected override void OnModelCreating(DbModelBuilder modelBuilder)
                {
                    modelBuilder.Conventions.Remove();
                }
    


    In general, Conventions is a pretty powerful thing. They allow you to configure the display of properties on the database based on various signs, enable / disable namespaces, and much more. You can read more about them here.

    Code-First really provides a lot of opportunities to manage the model code in the most convenient way for you. I believe that especially for small projects, as well as for mobile devices (yes, SQL Server CE 4.0 will be supported in Windows Phone Mango), this approach will be justified as much as possible.

    Also popular now: