Monday, April 16, 2012

Some tips for getting started with Telerik OpenAccess Fluent Mapping

If you are just starting using Telerik OpenAccess Fluent Mapping with Sql Server as database, you will probably need to set some settings in order to benefit most from this great ORM tool.
First of all, when defining your FluentMetadataSource, be sure to override the CreateModel() method and set the following properties:
public class DataMetadataSource : FluentMetadataSource
    {
        protected override Telerik.OpenAccess.Metadata.MetadataContainer CreateModel()
        {
            var model = base.CreateModel();
            model.DefaultMapping.NullForeignKey = true;
            model.NameGenerator.UseModelNames = true;
            return model;
        }
    }
The first one "NullForeignKey" will generate for you foreign keys on every column that is part of an association, keeping your data consistent. The next one "UseModelNames" will generate the name of the tables and the columns in your database to be the same as your .NET types. This will save you lots of dummy writing and copy pasting.

Another tip that will probably proof useful for you, is to save your model in the DataContext as private static variable and pass it to the constructor. This will boost the performance of your DataAccess layer.
public class DataContext : OpenAccessContext
    {
        static readonly MetadataContainer metadataContainer = new DataMetadataSource().GetModel();

        static BackendConfiguration backendConfiguration = new BackendConfiguration()
        {
            Backend = "mssql"
        };

        private const string DbConnection = "dbConnectionString";

        public DataContext()
            : base(DbConnection, backendConfiguration, metadataContainer)
        {
        }
    }

Finally, if your are just starting using this product, you will probably want to add the "Telerik.OpenAccess.Metadata.Fluent.Advanced" namespace in the using section where your mapping is defined. Since some of the features (like adding database indexes) are defined as extension methods in this namespace, for newbies (like me), that are not very familiar yet with the functionality that the product gives, this could be a great time saver.

Many thanks to Yosif Yosifov and Serge Ovanesyan for sharing this tips. If you have found any other interesting options, feel free to share them in the comments.