Linq2db sql

Date: 2017-11-03

https://discoverdot.net/projects/linq2db

var builder = MappingSchema.Default.GetFluentMappingBuilder();

builder.Entity<Product>()
    .HasTableName("Products")
    .HasSchemaName("dbo")
    .HasIdentity(x => x.ProductID)
    .HasPrimaryKey(x => x.ProductID)
    .Ignore(x => x.SomeNonDbProperty)
    .Property(x => x.TimeStamp)
        .HasSkipOnInsert()
        .HasSkipOnUpdate()
    .Association(x => x.Vendor, x => x.VendorID, x => x.VendorID, canBeNull: false)
    ;

//... other mapping configurations
using IBM.Data.DB2.iSeries;
using LinqToDB;
using LinqToDB.DataProvider;
using LinqToDB.DataProvider.DB2;
using LinqToDB.Mapping;
using System.Data;

    public class DbIseries : LinqToDB.Data.DataConnection
    {
        public DbIseries() : base(GetDataProvider(), GetConnection()) { }

        public ITable Product => GetTable();

        public ITable ArtikelGroep => GetTable();

        private static IDataProvider GetDataProvider()
        {
            return new DB2DataProvider("test.wan", DB2Version.zOS);
        }

        private static IDbConnection GetConnection()
        {
            LinqToDB.Common.Configuration.AvoidSpecificDataProviderAPI = true;

            var dbConnection = new iDB2Connection(@"DataSource=test.wan;UserID=user;Password=password;DataCompression=True;DEFAULT COLLECTION=ABC;Pooling=false;");
            return dbConnection;
        }

    }
    
    [Table(Name = "GS01HGR")]
    public class Product
    {
        [PrimaryKey, Identity, Column(Name = "HGRNUM")]
        public int ProductId { get; set; }

        [Column(Name = "HGROMS"), NotNull]
        public string Name { get; set; }
    }

    [Table(Name = "GS01AGR")]
    public class ArtikelGroep
    {
        [PrimaryKey, Identity, Column(Name = "AGRNUM")]
        public int ArtikelGroepId { get; set; }

        [Column(Name = "AGROMS"), NotNull]
        public string Name { get; set; }

        [Column(Name = "AGRHGR"), NotNull]
        public int HoofdGroepId { get; set; }
    }

        static void Main(string[] args)
        {
                try
            {
                using (var db = new DbIseries())
                {
                    var data = db.Product
                            .Join(db.ArtikelGroep,
                                a => a.ProductId,
                                b => b.HoofdGroepId,
                                (a, b) => new { a, b })
                            .Where(p => p.a.ProductId < 25).OrderBy(p => p.a.Name);
                    var records = data.ToList();

                    String results = JsonConvert.SerializeObject(records, Formatting.Indented);
                    Console.WriteLine(results); ;
                }

            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
            Console.ReadKey();

        }
private static MappingSchema GetMappingSchema()
{
    var mappingSchema = new MappingSchema();
    var mappers = typeof(BaseAfwezigheidRepository<T>).Assembly.GetTypes().Where(t => t.BaseType == typeof(BaseDataMapper<T>));
    foreach(var mapper in mappers) { 
        Activator.CreateInstance(mapper, mappingSchema);
    }
    return mappingSchema;
}

public class BaseDataMapper<T>
{
    protected readonly EntityMappingBuilder<T> Map;

    protected BaseDataMapper(MappingSchema mappingSchema)
    {
        Map = mappingSchema.GetFluentMappingBuilder().Entity<T>();
    }
}

Creating your POCOs

In the previous example we assign an entire Category object to our product, but what if we want all the fields in our Product class, but we don’t want to specify every field by hand? Unfortunately, we cannot write this:

from p in db.Product
from c in db.Category.Where(q => q.CategoryID == p.CategoryID).DefaultIfEmpty()
select new Product(c);

The query above assumes the Product class has a constructor that takes in a Category object. The query above won’t work, but we can work around that with the following query:

from p in db.Product
from c in db.Category.Where(q => q.CategoryID == p.CategoryID).DefaultIfEmpty()
select Product.Build(p, c);

For this to work, we need a function in the Product class that looks like this:

public static Product Build(Product product, Category category)
{
  if (product != null)
  {
    product.Category = category;
  }
  return product;
}

One caveat with this approach is that if you’re using it with composed queries (see example above) the select Build part has to come only in the final select.

9210cookie-checkLinq2db sql