How to Use Entity Framework Fluent API

How to Change Entity Framework Default Conventions, when Mapping Data ?

There are 3 ways.

1. Entity Framework Fluent API

2. Fluent Validation
       - Validation Library for .NET
       - This uses a fluent interface and lambda expressions for building validation rules
          for your business objects

3. Data Annotations 
          - Annotations only cover a subset of the Fluent Validation functionality


Entity Framework Fluent API

       
What is Entity Framework Fluent API ?
  • When working with Entity Framework Code First the default behavior is to map your POCO classes to tables using a set of conventions baked into Entity Framework
  • Sometimes, however you cannot or do not want to follow those conventions and need to map entities to something other than what the conventions dictate
  • For such a scenario you can use Fluent API
  • Can be Used Only with Code First Development
  • This is used to define the mapping between your objects and the database

What Does Fluent API  do ?
  • The Code First Fluent API is most commonly accessed by overriding the OnModelCreating method on your derived DbContext class

Which Tasks can be Achieved by using Fluent API ?

1. Property Mapping

2. Type Mapping

3. Configuring Relationships

On This Article I will explain Property Mapping with Fluent API.  

Articles Sample Code Here

1. Property Mapping

    - is used to configure attributes for each property belonging to an entity or complex type
    - is used to obtain a configuration object for a given property
    - the options on the configuration object are specific to the type being configured
                 e.g. IsUnicode is available only on string properties 

  • How to Configure a Primary Key ?
          - The HasKey method is used to configure the InstructorID primary key on the
             OfficeAssignment type

       modelBuilder.Entity<OfficeAssignment>().HasKey(t => t.InstructorId);

  • How to Configure a Composite Primary Key ?
         - DepartmentId and Name properties to be the composite primary key of the
           Department type

      modelBuilder.Entity<Department>()
           .HasKey(t => new { t.DepartmentId, t.Name });

  • How to Switch off Identity for Numeric Primary Keys ?
         - DepartmentId property value will not be generated by the database

      modelBuilder.Entity<Department>()
          .Property(t => t.DepartmentId)
          .HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);

  • How to Specify the Maximum Length on a Property ?
         - Name property should be no longer than 50 characters

         - If you make the value longer than 50 characters, you will get a 
            DbEntityValidationException exception

         - If Code First creates a database from this model it will also set the
            maximum length of the Name column to 50 characters 

      modelBuilder.Entity<Department>().Property(t => t.Name).HasMaxLength(50);

  • How to Configure the Property to be Required ?
         - Name property is required

         - If you do not specify the Name, you will get a 
            DbEntityValidationException exception

         - If Code First creates a database from this model then the column used to store
            this property will be non-nullable

      modelBuilder.Entity<Department>().Property(t => t.Name).IsRequired(); 

  • How to Specify Not to Map a CLR Property to a Column in the Database ?

      modelBuilder.Entity<Department>().Ignore(t => t.Budget);

  • How to Map a CLR Property to a Specific Column in the Database ?

          - Maps the Name CLR property to the DepartmentName database column

       modelBuilder.Entity<Department>()
                .Property(t => t.Name)
                .HasColumnName("DepartmentName");

  • How to Rename a Foreign Key That Is Not Defined in the Model ?
          - If you choose not to define a foreign key on a CLR type,
          - But want to specify what name it should have in the database

       modelBuilder.Entity<Course>()
          .HasRequired(c => c.Department)
          .WithMany(t => t.Courses)
          .Map(m => m.MapKey("ChangedDepartmentId"));

  • How to Configure whether a String Property Supports Unicode Content ?
          - By default strings are Unicode (nvarchar in SQL Server)
          - You can use the IsUnicode method to specify that a string should be of varchar type

      modelBuilder.Entity<Department>().Property(t => t.Name).IsUnicode(false);

  • How to Configure the Data Type of a Database Column ?
         - The HasColumnType method enables mapping to different representations
            of the same basic type

         - Using this method does not enable you to perform any conversion
            of the data at run time

         - Note that : IsUnicode is the preferred way of setting columns to varchar,
            as it is database agnostic

     modelBuilder.Entity<Department>()
                 .Property(p => p.Name)
                 .HasColumnType("varchar");

  • How to Configure Properties on a Complex Type ?

         Way 1 : You can call Property on ComplexTypeConfiguration

       modelBuilder.ComplexType<Details>()
                   .Property(t => t.Location)
                   .HasMaxLength(20);

        Way 2 : You can also use the dot notation to access a property of a complex type

       modelBuilder.Entity<OnsiteCourse>()
            .Property(t => t.Details.Location)
            .HasMaxLength(20);

  • How to Configure a Property to Be Used as an Optimistic Concurrency Token ?

       Way 1 : You can use either the ConcurrencyCheck attribute
                     or the IsConcurrencyToken method

      modelBuilder.Entity<OfficeAssignment>()
                  .Property(t => t.Timestamp)
                  .IsConcurrencyToken();

      Way 2 : You can also use the IsRowVersion method

     modelBuilder.Entity<OfficeAssignment>()
                 .Property(t => t.Timestamp)
                 .IsRowVersion();
Conclusion
  • You can use Fluent API with Code First development, when you want to override the default conventions maintained by the Entity Framework
  • I will explain Type Mapping and Configuring Relationships with my future Blog Post
  • So Try This and Enjoy it

I hope this helps to You.Comments and feedback greatly appreciated.

Happy Coding

Articles You Might Like

Stay Tuned: Ill be Back with Type Mapping and Configuring Relationships

Read More..

Advantages Accrued From Use Of Project Management Software For Architects And Engineers

By Allyson Burke


The toughest battle for any sensible technician is in designing a layout for his or her project to suit certain specifications. Through the aid of a project management software for architects and engineers for instance, there is a realization of some of these factors without extreme efforts. Thus, one can branch this into other aspects of the mission that do not often receive the proper attention.

Before commencing any project, then there has to be a certain acceptable level of understanding of what is possible and what is not. That is the entire function of a strategy, an incorporated feature in this program. By allowing one decide on what and what they do not want, it creates a definition or picture of what one should consider efficient and how to be almost accurate. The hardest part of a project consequently done, other components may come in.

Organization is another element that makes running of any system simple and understandable. After creating a way of tackling the details, then one can begin placing all things in a chronological manner depending on its weight or importance, or by using any other model. The features available make selection, integration or deletion a click away, as opposed to working on papers and making a mess of everything.

What creates a sensible flow in the models is the merging in the entire process. After obtaining necessary data and feeding it into the program, there is a chance to preview the exactness of a product and its weaknesses. By opening up to the right choices, the team of experts gets to make modifications whenever convenient instead of rushing and making blunders.

Because there is a need of a team, due to specialization and for efficiency purposes, it acts as a central information retriever. This process comes before the compilation process but its benefit remains relevant. By controlling all the information made accessible by the members of the team, it enables each of them to see it and suggest changes or get explanation as to its importance.

The number of projects that it can handle is great, and thus the amount of data it holds tends to be similarly huge. The only way to keep and distinguish between these details is by collecting, classifying, and storing it in a central area in the processor. This works best for cases when the users want to retrieve or compare the information.

The good thing about having a common program that designs a number of prototypes is the issue of referencing later. Everything becomes available for analysis and comparison in case one needs to produce a similar result. It thus serves a unique purpose that such a program should.

The mystery of the existent connection between creativity and machinery becomes a clear record here. Therefore, the significance of a project management software for architects and engineers does not have functional limitations thereof. It works with and for the team or individuals present to fulfill their desire in the best way they can imagine.




About the Author:



Read More..

Facts About The Use Of Webinar Software

By Ken Morrison


A webinar is a virtual seminar in which attendees connect to a network like the internet and listen and sometimes see a presentation that is organized on a particular topic. Instead of gathering people together in a conference hall, the presentation is made through virtual space. Webinar software is a computer program that assists in arranging, running and managing the conference.

There are various software options, some are free while others have to be purchased to get licenses.The free versions are usually limited in what functions they can perform. The purchased versions usually have different packages depending on your intended number of attendees. The higher the number the more it costs.

Recording a meeting is possible using this application as long as the feature is enabled. This recording can then be used for reviewing at another time or it can be given to participants or even sold. Another advantage is that most programs have a video streaming capacity where your webcam can be used to broadcast images. This is usually secure and therefore better than many other methods of hosting through webcam broadcasts.

Attendee participation is also possible whereby they can answer questionnaires; participate in polling and any other such forums that have been set up. The level of participation depends on the capabilities of the application and the features enabled. Interaction between the presenter(s) and the audience is also possible; this is because the webinars are usually real-time. The presenter can therefore answer any questions or provide ways to access further information.

The cost of using the program is also much less than other options. It does not involve any operating costs and therefore the only cost is buying the license. It can also be used for other purposes like video conferencing at work or offering online courses for learning institutions.

Webinars therefore provide a great solution for interaction with people and information sharing. Online meeting software provides a solution for companies that require constant interaction with people.




About the Author:



Read More..

Blog Archive

Powered by Blogger.