Code Monkey home page Code Monkey logo

linq2db.linqpad's Introduction

LINQ to DB

Discord NuGet Version and Downloads count License "good first issue" tasks

Master branch build Latest build

LINQ to DB is the fastest LINQ database access library offering a simple, light, fast, and type-safe layer between your POCOs and your database.

Architecturally it is one step above micro-ORMs like Dapper, Massive, or PetaPoco, in that you work with LINQ expressions, not with magic strings, while maintaining a thin abstraction layer between your code and the database. Your queries are checked by the C# compiler and allow for easy refactoring.

However, it's not as heavy as LINQ to SQL or Entity Framework. There is no change-tracking, so you have to manage that yourself, but on the positive side you get more control and faster access to your data.

In other words LINQ to DB is type-safe SQL.

Development version nuget feed (how to use)

You can follow our twitter bot to receive notifications about new releases. Note that currently it is only release notification bot and we don't monitor questions there.

Standout Features

See Github.io documentation for more details.

Code examples and demos can be found here or in tests.

Release notes page.

Related Linq To DB and 3rd-party projects

Notable open-source users:

  • nopCommerce - popular open-source e-commerce solution
  • OdataToEntity - library to create OData service from database context
  • SunEngine - site, blog and forum engine

Unmantained projects:

Configuring connection strings

Passing Into Constructor

You can simply pass connection string into DataConnection or DataContext constructor using DataOptions class.

Minimal configuration example:

var db = new DataConnection(
  new DataOptions()
    .UseSqlServer(@"Server=.\;Database=Northwind;Trusted_Connection=True;"));

Use connection configuration action to setup SqlClient-specific authentication token:

var options = new DataOptions()
  .UseSqlServer(connectionString, SqlServerVersion.v2017, SqlServerProvider.MicrosoftDataSqlClient)
  .UseBeforeConnectionOpened(cn =>
    {
        ((SqlConnection)cn).AccessToken = accessToken;
    });

// pass configured options to data context constructor
var dc = new DataContext(options);

Tip

There are a lot of configuration methods on DataOptions you can use.

[!TIP] It is recommended to create configured DataOptions instance once and use it everywhere. E.g. you can register it in your DI container.

Using Config File (.NET Framework)

In your web.config or app.config make sure you have a connection string (check this file for supported providers):

<connectionStrings>
  <add name="Northwind" 
    connectionString = "Server=.\;Database=Northwind;Trusted_Connection=True;" 
    providerName     = "SqlServer" />
</connectionStrings>

Using Connection String Settings Provider

Alternatively, you can implement custom settings provider with ILinqToDBSettings interface, for example:

public class ConnectionStringSettings : IConnectionStringSettings
{
    public string ConnectionString { get; set; }
    public string Name             { get; set; }
    public string ProviderName     { get; set; }
    public bool   IsGlobal         => false;
}

public class MySettings : ILinqToDBSettings
{
    public IEnumerable<IDataProviderSettings> DataProviders
        => Enumerable.Empty<IDataProviderSettings>();

    public string DefaultConfiguration => "SqlServer";
    public string DefaultDataProvider  => "SqlServer";

    public IEnumerable<IConnectionStringSettings> ConnectionStrings
    {
        get
        {
            // note that you can return multiple ConnectionStringSettings instances here
            yield return
                new ConnectionStringSettings
                {
                    Name             = "Northwind",
                    ProviderName     = ProviderName.SqlServer,
                    ConnectionString =
                        @"Server=.\;Database=Northwind;Trusted_Connection=True;"
                };
        }
    }
}

And later just set on program startup before the first query is done (Startup.cs for example):

DataConnection.DefaultSettings = new MySettings();

Use with ASP.NET Core and Dependency Injection

See article.

Define POCO class

You can generate POCO classes from your database using linq2db.cli dotnet tool.

Alternatively, you can write them manually and map to database using mapping attributes or fluent mapping configuration. Also you can use POCO classes as-is without additional mappings if they use same naming for classes and properties as table and column names in database.

Configuration using mapping attributes

using System;
using LinqToDB.Mapping;

[Table("Products")]
public class Product
{
  [PrimaryKey, Identity]
  public int ProductID { get; set; }

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

  [Column]
  public int VendorID { get; set; }

  [Association(ThisKey = nameof(VendorID), OtherKey=nameof(Vendor.ID))]
  public Vendor Vendor { get; set; }

  // ... other columns ...
}

This approach involves attributes on all properties that should be mapped. This way lets you to configure all possible things linq2db ever supports. There is one thing to mention: if you add at least one attribute into POCO, all other properties should also have attributes, otherwise they will be ignored:

using System;
using LinqToDB.Mapping;

[Table("Products")]
public class Product
{
  [PrimaryKey, Identity]
  public int ProductID { get; set; }

  // Property `Name` will be ignored as it lacks `Column` attibute.
  public string Name { get; set; }
}

Fluent Configuration

This method lets you configure your mapping dynamically at runtime. Furthermore, it lets you to have several different configurations if you need so. You will get all configuration abilities available with attribute configuration. These two approaches are interchangeable in their abilities. This kind of configuration is done through the class MappingSchema.

With Fluent approach you can configure only things that require it explicitly. All other properties will be inferred by linq2db:

// IMPORTANT: configure mapping schema instance only once
// and use it with all your connections that need those mappings
// Never create new mapping schema for each connection as
// it will seriously harm performance
var myFluentMappings = new MappingSchema();
var builder       = mappingSchema.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

// commit configured mappings to mapping schema
builder.Build();

In this example we configured only three properties and one association. We let Linq To DB to infer all other properties as columns with same name as property.

To use your MappingSchema instance you should pass it DataConnection or DataContext constructor:

var options = new DataOptions()
    .UseSqlServer(@"Server=.\;Database=Northwind;Trusted_Connection=True;")
    .UseMappingSchema(myFluentMappings);

var db = new DataConnection(option);

Inferred Configuration

This approach involves no attributes at all. In this case Linq To DB will use POCO's name as table name and property names as column names (with exact same casing, which could be important for case-sensitive databases). This might seem to be convenient, but there are some restrictions:

  • Linq To DB will not infer primary key even if class has property called ID;
  • it will not infer nullability of reference types if you don't use nullable reference types annotations;
  • associations will not be automatically configured.
using System;
using LinqToDB.Mapping;

public class Product
{
  public int    ProductID { get; set; }

  public string Name      { get; set; }

  public int    VendorID  { get; set; }

  public Vendor Vendor    { get; set; }

  // ... other columns ...
}

This way Linq To DB will auto-configure Product class to map to Product table with fields ProductID, Name, and VendorID. POCO will not get ProductID property treated as primary key. And there will be no association with Vendor.

This approach is not generally recommended.

DataConnection class

At this point LINQ to DB doesn't know how to connect to our database or which POCOs go with what database. All this mapping is done through a DataConnection class:

public class DbNorthwind : LinqToDB.Data.DataConnection
{
  public DbNorthwind() : base("Northwind") { }

  public ITable<Product>  Product  => this.GetTable<Product>();
  public ITable<Category> Category => this.GetTable<Category>();

  // ... other tables ...
}

We call the base constructor with the "Northwind" parameter. This parameter (called configuration name) has to match the name="Northwind" we defined above as name of our connection string. We also added convenience properties for Product and Category mapping classes to write LINQ queries.

And now let's get some data:

using LinqToDB;
using LinqToDB.Common;

public static List<Product> GetProducts()
{
  using var db = new DbNorthwind();

  var query = from p in db.Product
                where p.ProductID > 25
                orderby p.Name descending
                select p;

  return query.ToList();
}

Make sure you always wrap your DataConnection class (in our case DbNorthwind) in a using statement. This is required for proper resource management, like releasing the database connections back into the pool (more details).

Queries

Selecting Columns

Most times we get the entire row from the database:

from p in db.Product
where p.ProductID == 5
select p;

However, sometimes getting all the fields is too wasteful so we want only certain fields, but still use our POCOs; something that is challenging for libraries that rely on object tracking, like LINQ to SQL.

from p in db.Product
orderby p.Name descending
select new Product
{
  Name = p.Name
};

Composing queries

Rather than concatenating strings we can 'compose' LINQ expressions. In the example below the final SQL will be different if onlyActive is true or false, or if searchFor is not null.

public static Product[] GetProducts(bool onlyActive, string searchFor)
{
  using var db = new DbNorthwind();
  var products = from p in db.Product 
                   select p;

  if (onlyActive)
  {
    products = from p in products 
               where !p.Discontinued 
               select p;
  }

  if (searchFor != null)
  {
    products = from p in products 
                 where p.Name.Contains(searchFor) 
                 select p;
  }

  return products.ToArray();
}

Paging

A lot of times we need to write code that returns only a subset of the entire dataset. We expand on the previous example to show what a product search function could look like.

Keep in mind that the code below will query the database twice. Once to find out the total number of records, something that is required by many paging controls, and once to return the actual data.

public static List<Product> Search(
                  string  searchFor,
                  int     currentPage,
                  int     pageSize,
                  out int totalRecords)
{
  using var db = new DbNorthwind();
  var products = from p in db.Product 
                   select p;

  if (searchFor != null)
  {
    products = from p in products 
               where p.Name.Contains(searchFor) 
               select p;
  }

  totalRecords = products.Count();

  return products.Skip((currentPage - 1) * pageSize).Take(pageSize).ToList();
}

Joins

This assumes we added a Category class, just like we did with the Product class, defined all the fields, and defined table access property in our DbNorthwind data access class. We can now write an INNER JOIN query like this:

from p in db.Product
join c in db.Category on p.CategoryID equals c.CategoryID
select new Product
{
  Name = p.Name,
  Category = c
};

and a LEFT JOIN query like this:

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

More samples are here

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.

Insert

At some point we will need to add a new Product to the database. One way would be to call the Insert extension method found in the LinqToDB namespace; so make sure you import that.

using LinqToDB;

using var db = new DbNorthwind();
db.Insert(product);

This inserts all the columns from our Product class, but without retrieving the generated identity value. To do that we can use InsertWith*Identity methods, like this:

using LinqToDB;

using var db = new DbNorthwind();
product.ProductID = db.InsertWithInt32Identity(product);

There is also InsertOrReplace that updates a database record if it was found by primary key or adds it otherwise.

If you need to insert only certain fields, or use values generated by the database, you could write:

using LinqToDB;

using var db = new DbNorthwind();
db.Product
  .Value(p => p.Name, product.Name)
  .Value(p => p.UnitPrice, 10.2m)
  .Value(p => p.Added, () => Sql.CurrentTimestamp)
  .Insert();

Use of this method also allows us to build insert statements like this:

using LinqToDB;

using var db = new DbNorthwind();
var statement = db.Product
                    .Value(p => p.Name, product.Name)
                    .Value(p => p.UnitPrice, 10.2m);

if (storeAdded) statement.Value(p => p.Added, () => Sql.CurrentTimestamp);

statement.Insert();

Update

Updating records follows similar pattern to Insert. We have an extension method that updates all the columns in the database:

using LinqToDB;

using var db = new DbNorthwind();
db.Update(product);

And we also have a lower level update mechanism:

using LinqToDB;

using var db = new DbNorthwind();
db.Product
  .Where(p => p.ProductID == product.ProductID)
  .Set(p => p.Name, product.Name)
  .Set(p => p.UnitPrice, product.UnitPrice)
  .Update();

Similarly, we can break an update query into multiple pieces if needed:

using LinqToDB;

using var db = new DbNorthwind();
var statement = db.Product
                    .Where(p => p.ProductID == product.ProductID)
                    .Set(p => p.Name, product.Name);

if (updatePrice) statement = statement.Set(p => p.UnitPrice, product.UnitPrice);

statement.Update();

You're not limited to a single record update. For example, we could discontinue all the products that are no longer in stock:

using LinqToDB;

using var db = new DbNorthwind();
db.Product
  .Where(p => p.UnitsInStock == 0)
  .Set(p => p.Discontinued, true)
  .Update();

Delete

Similar to how you update records, you can also delete records:

using LinqToDB;

using var db = new DbNorthwind();
db.Product
  .Where(p => p.Discontinued)
  .Delete();

Bulk Copy

Bulk copy feature supports the transfer of large amounts of data into a table from another data source. For more details read this article.

using LinqToDB.Data;

[Table("ProductsTemp")]
public class ProductTemp
{
  [PrimaryKey]
  public int ProductID { get; set; }

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

  // ... other columns ...
}

var list = new List<ProductTemp>();

// ... populate list ...

using var db = new DbNorthwind();
db.BulkCopy(list);

Transactions

Using database transactions is easy. All you have to do is call BeginTransaction() on your DataConnection, run one or more queries, and then commit the changes by calling CommitTransaction(). If something happened and you need to roll back your changes you can either call RollbackTransaction() or throw an exception.

using var db = new DbNorthwind();
db.BeginTransaction();
// or
//using var tr = db.BeginTransaction();
  
  // ... select / insert / update / delete ...

if (somethingIsNotRight)
{
  db.RollbackTransaction();
  // or
  // tr.Rollback();
}
else
{
  db.CommitTransaction();
  // or
  // tr.Commit();
}

Also, you can use .NET built-in TransactionScope class:

using var transaction = new TransactionScope();
// or for async code
// using var transaction = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled);
using var db = new DbNorthwind();
...
transaction.Complete();

It should be noted that there are two base classes for your "context" class: LinqToDB.Data.DataConnection and LinqToDB.DataContext. The key difference between them is in connection retention behaviour. DataConnection opens connection with first query and holds it open until dispose happens. DataContext behaves the way you might used to with Entity Framework: it opens connection per query and closes it right after query is done.

This difference in behavior matters when used with TransactionScope:

using var db = new LinqToDB.Data.DataConnection("provider name", "connection string");

var product = db.GetTable<Product>()
  .FirstOrDefault(); // connection opened here

var scope = new TransactionScope();
// this transaction was not attached to connection
// because it was opened earlier

product.Name = "Lollipop";
db.Update(product);

scope.Dispose();

// no transaction rollback happed, "Lollipop" has been saved

A DataConnection is attached with ambient transaction in moment it is opened. Any TransactionScopes created after the connection is created will no effect on that connection. Replacing DataConnection with DataContext in code shown earlier will make transaction scope work as expected: the created record will be discarded with the transaction.

Although, DataContext appears to be the right class to choose, it is strongly recommended to use DataConnection instead. It's default behaviour might be changed with setting CloseAfterUse property to true:

public class DbNorthwind : LinqToDB.Data.DataConnection
{
  public DbNorthwind() : base("Northwind")
  {
    (this as IDataContext).CloseAfterUse = true;
  }
}

Merge

Here you can read about SQL MERGE support.

Window (Analytic) Functions

Here you can read about Window (Analytic) Functions support.

MiniProfiler

If you would like to use MiniProfiler or other profiling tool that wraps ADO.NET provider classes, you need to configure our regular DataConnection to use wrapped connection.

// example of SQL Server-backed data connection with MiniProfiler enabled for debug builds
public class DbDataContext : DataConnection
{
// let's use profiler only for debug builds
#if !DEBUG

  // regular non-profiled constructor
  public DbDataContext() : base("Northwind") {}
  
#else
  public DbDataContext()
      : base(
          new DataOptions()
            .UseSqlServer(connectionString, SqlServerVersion.v2012)
            .UseConnectionFactory(GetConnection)
            .UseInterceptor(new UnwrapProfilerInterceptor()))
  {
  }

  // wrap connection into profiler wrapper
  private static DbConnection GetConnection(DataOptions options)
  {
     // create provider-specific connection instance. SqlConnection in our case
     var dbConnection = new SqlConnection(options.ConnectionOptions.ConnectionString);

     // wrap it by profiler's connection implementation
     return new StackExchange.Profiling.Data.ProfiledDbConnection(
                                                 dbConnection,
                                                 MiniProfiler.Current);
  }

  // define UnwrapDataObjectInterceptor
  sealed class UnwrapProfilerInterceptor : UnwrapDataObjectInterceptor
  {
    public override DbConnection UnwrapConnection(IDataContext dataContext, DbConnection connection)
    {
      return connection is ProfiledDbConnection c ? c.WrappedConnection : connection;
    }

    public override DbTransaction UnwrapTransaction(IDataContext dataContext, DbTransaction transaction)
    {
       return transaction is ProfiledDbTransaction t ? t.WrappedTransaction : transaction;
    }

    public override DbCommand UnwrapCommand(IDataContext dataContext, DbCommand command)
    {
      return command is ProfiledDbCommand c ? c.WrappedCommand : command;
    }

    public override DbDataReader UnwrapDataReader(IDataContext dataContext, DbDataReader dataReader)
    {
      return dataReader is ProfiledDbDataReader dr ? dr.WrappedReader : dataReader;
    }
  }
#endif
}

More

Still have questions left? Check out our documentation site and FAQ

linq2db.linqpad's People

Contributors

db2222 avatar igor-tkachev avatar ili avatar jogibear9988 avatar macewindu avatar mmbilinski avatar roychase avatar sdanyliv avatar viceroypenguin avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

linq2db.linqpad's Issues

LINQPad 5 AnyCPU error - BadImageFormatException on IBM.Data.DB2.dll

Windows 10 64-bit.

If using LINQPad 5 - linq2db plugin works fine.
if using LINQPad 5 AnyCPU - linq2db plugin throws exception
untitled

I think this happens because IBM.Data.DB2.dll has platform target x86
If I open IBM.Data.DB2.dll from Redist folder in this repositiry in JetBrains dotPeek, I can see picture
untitled2

So I think linq2db plugin should provide two versions on IBM.Data.DB2.dll - x86 and x64 bit editions.
You can do this using bindingRedirect feature.

Super!

Thank you very much for this driver!!!
In the DataConnection Options, is there a way to fech/populate only a few tables when loading?
Otherwise I would get only a timeout, in my case (the dbo schema contains too many tables).
Thanks again and keep up the good work! :-)

Sybase.Data.AseClient.AseException: The command has timed out.

   at Sybase.Data.AseClient1.AseCommand.CheckResult(Int32 res)
   at Sybase.Data.AseClient1.AseCommand.Execute(CommandBehavior commandBehavior)
   at Sybase.Data.AseClient1.AseCommand._ExecuteReader(CommandBehavior commandBehavior)
   at Sybase.Data.AseClient1.AseCommand.ExecuteReader(CommandBehavior commandBehavior)
   at Sybase.Data.AseClient.AseCommand.ExecuteDbDataReader(CommandBehavior behavior)
   at System.Data.Common.DbCommand.System.Data.IDbCommand.ExecuteReader(CommandBehavior behavior)
   at System.Data.Common.DbDataAdapter.FillInternal(DataSet dataset, DataTable[] datatables, Int32 startRecord, Int32 maxRecords, String srcTable, IDbCommand command, CommandBehavior behavior)
   at System.Data.Common.DbDataAdapter.Fill(DataTable[] dataTables, Int32 startRecord, Int32 maxRecords, IDbCommand command, CommandBehavior behavior)
   at System.Data.Common.DbDataAdapter.Fill(DataTable dataTable)
   at Sybase.Data.AseClient.AseConnection.GetSchema(String collectionName, String[] restrictionValues)
   at Sybase.Data.AseClient.AseConnection.GetSchema(String collectionName)
   at LinqToDB.DataProvider.Sybase.SybaseSchemaProvider.GetProcedureParameters(DataConnection dataConnection) in i:\linq2db\Source\DataProvider\Sybase\SybaseSchemaProvider.cs:line 181
   at LinqToDB.SchemaProvider.SchemaProviderBase.GetSchema(DataConnection dataConnection, GetSchemaOptions options) in i:\linq2db\Source\SchemaProvider\SchemaProviderBase.cs:line 188
   at LinqToDB.LINQPad.SchemaAndCodeGenerator.<GetItemsAndCode>d__11.MoveNext() in C:\projects\linq2db-linqpad\Source\SchemaAndCodeGenerator.cs:line 60
   at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
   at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
   at LinqToDB.LINQPad.LinqToDBDriver.GetSchemaAndBuildAssembly(IConnectionInfo cxInfo, AssemblyName assemblyToBuild, String& nameSpace, String& typeName) in C:\projects\linq2db-linqpad\Source\LinqToDBDriver.cs:line 225
   at Sybase.Data.AseClient1.AseCommand.CheckResult(Int32 res)
   at Sybase.Data.AseClient1.AseCommand.Execute(CommandBehavior commandBehavior)
   at Sybase.Data.AseClient1.AseCommand._ExecuteReader(CommandBehavior commandBehavior)
   at Sybase.Data.AseClient1.AseCommand.ExecuteReader(CommandBehavior commandBehavior)
   at Sybase.Data.AseClient.AseCommand.ExecuteDbDataReader(CommandBehavior behavior)
   at System.Data.Common.DbCommand.System.Data.IDbCommand.ExecuteReader(CommandBehavior behavior)
   at System.Data.Common.DbDataAdapter.FillInternal(DataSet dataset, DataTable[] datatables, Int32 startRecord, Int32 maxRecords, String srcTable, IDbCommand command, CommandBehavior behavior)
   at System.Data.Common.DbDataAdapter.Fill(DataTable[] dataTables, Int32 startRecord, Int32 maxRecords, IDbCommand command, CommandBehavior behavior)
   at System.Data.Common.DbDataAdapter.Fill(DataTable dataTable)
   at Sybase.Data.AseClient.AseConnection.GetSchema(String collectionName, String[] restrictionValues)
   at Sybase.Data.AseClient.AseConnection.GetSchema(String collectionName)
   at LinqToDB.DataProvider.Sybase.SybaseSchemaProvider.GetProcedureParameters(DataConnection dataConnection) in i:\linq2db\Source\DataProvider\Sybase\SybaseSchemaProvider.cs:line 181
   at LinqToDB.SchemaProvider.SchemaProviderBase.GetSchema(DataConnection dataConnection, GetSchemaOptions options) in i:\linq2db\Source\SchemaProvider\SchemaProviderBase.cs:line 188
   at LinqToDB.LINQPad.SchemaAndCodeGenerator.<GetItemsAndCode>d__11.MoveNext() in C:\projects\linq2db-linqpad\Source\SchemaAndCodeGenerator.cs:line 60
   at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
   at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
   at LinqToDB.LINQPad.LinqToDBDriver.GetSchemaAndBuildAssembly(IConnectionInfo cxInfo, AssemblyName assemblyToBuild, String& nameSpace, String& typeName) in C:\projects\linq2db-linqpad\Source\LinqToDBDriver.cs:line 225

LinqPad 5

The issue is in linqpad5 a query with left join is performaing a weird inner join and adding a new ref to the left side of the join instead of using the alias defined for the left side of the table.

This is my query

	var persistedDomainEvent = (from p in PersistedDomainEvent
								from c in DomainEventConsumptionLogEntry.LeftJoin(c => p.Id == c.PersistedDomainEvent.Id )
								//where p.ScheduledTimeUtc >= pastTime && p.ScheduledTimeUtc <= futureTime
								//&& p.DomainEventJson.Contains("540593036")
								orderby p.ScheduledTimeUtc descending

								select new { p, c }).Take(1000);

and this is whats output

--  SqlServer.2008
SELECT TOP (1000)
	[t2].[Id],
	[t2].[CausingCommand],
	[t2].[RaisedTimeUtc],
	[t2].[ScheduledTimeUtc],
	[t2].[DomainEventType],
	[t2].[DomainEventJson],
	[t2].[Priority],
	[c1].[Id] as [Id1],
	[c1].[ConsumedTime],
	[c1].[CompletedTime],
	[c1].[Consumer],
	[c1].[Failures],
	[c1].[PersistedDomainEvent_id],
	[c1].[FailureRerunEventId]
FROM
	[dbo].[PersistedDomainEvent] [t2]
		LEFT JOIN [dbo].[DomainEventConsumptionLogEntry] [c1]
-->>>>>>>>>>>>>>>weird stuff happening here
			INNER JOIN [dbo].[PersistedDomainEvent] [t1] ON [c1].[PersistedDomainEvent_id] = [t1].[Id]
		ON [t2].[Id] = [t1].[Id]
ORDER BY
	[t2].[ScheduledTimeUtc] DESC

Should it be

LEFT JOIN [dbo].[DomainEventConsumptionLogEntry] [c1] ON [c1].[PersistedDomainEvent_id] = [t2].[Id]

Sql.Expression attribute not working from MyExtensions in LINQPad

I have this extension method defined in the MyExtensions file in LINQPad:

[LinqToDB.Sql.Expression("({0} IS NULL OR Len({0}) IS NOT NULL AND Len({0}) = 0)", IsPredicate = true)]
public static bool IsNullOrEmpty(this string str) => string.IsNullOrEmpty(str);

However, when I try and use it in another query it doesn't work and I get:
LinqException: 'i.TableProperty.IsNullOrEmpty()' cannot be converted to SQL.

If I move the extension method to the actual query file it works just fine, however.
I do apologize if this isn't the right place for this. I'm not too familiar with attributes, so not sure if this is me misunderstanding something (probably) or something with LINQPad.

MS Access

Describe your issue.

If you have a question, first try to check our documentation, especially FAQ and search in issues and discussions - maybe your question already answered there.

If you still have questions or want to start general discussion, please create new topic in discussions.

If you are seeing an exception, include the full exceptions details (message and stack trace).

Exception message:
Stack trace:

Error instantiating type MSAccessDataContextDriver.MSAccessDataContextDriver in C:\AppData\Local\LINQPad\Drivers\DataContext\NetCore\MSAccessDataContextDriver\MSAccessDataContextDriver.dll
  - Driver assembly targets .NET Framework. Your driver assembly must target .NET Core.   at LINQPad.Extensibility.DataContext.DriverProxy.Instantiator.Instantiate(String assemblyPath, String typeName, String internalID)

### Steps to reproduce
Try to open an existing connection from LinqPad 6.
Error message.

```c#
<code with error and mapping classes>

Environment details

linq2db version: 4.1.0.0
Database Server: MS Access
Database Provider: Microsoft Access (ODBC)
Operating system: Windows 10
.NET Framework: 4.6

Vulnerability Issue

Hi there I am using this driver and I am seeing these errors. Can it be updated to address the vulnerabilities?
image001

Using this driver results in a warning (System.DirectoryServices.Protocols 5.0.0 vulnerability)

When using this driver in LINQPad 7.3.9, a warning is emitted at the beginning of the run:

Warning: LINQPad has identified the following vulnerabilties in NuGet package System.DirectoryServices.Protocols 5.0.0:

Level 1 (Moderate): GHSA-9cxh-gqpx-qc5m
Try updating NuGet packages to latest. You can suppress this warning in Edit | Preferences > Advanced > Execution.

The dependency tree seems to be:

This should be resolved by bumping the linq2db version used to either 3.7.0 or 4.0.0.

Can't run SQL against MS Access (unable to obtain a DbFactory)

I posted this on the LinqPad forum as well, because I'm not sure if it's a limitation of LinqPad or an issue with this driver.

When I make a connection to an MS Access db (either OleDb or ODBC), I'm able to test the connection successfully, I'm able to expand the connection node and see all the tables, and I'm able to run C# code using the connection. But if I choose SQL as the language and try to execute a straight query, I get an error, "Unable to obtain a DbFactory for the connection."

Use relaxed dependency check for .NETFramework version

Installation on .NETFramework 4.6.1 / 4.7.2 failed

Could not install package 'linq2db.LINQPad 3.3.3'. You are trying to install this package into a project that targets '.NETFramework,Version=v4.7.2', but the package does not contain any assembly references or content files that are compatible with that framework. For more information, contact the package author.

SQL vs C# Language differences in table and query names

I have discovered after upgrading the Linq To DB driver to version 5 that all of my database queries that reference a table name or field name containing an underscore character are broken and require modification to work.

I have found that when displaying the table names and fields in the Database browser (left top panel in LINQPad) while the SQL Language option is chosen, the fields have the expected (unmodified) names. Selecting any language option other than SQL displays modified entity names.

This breaking change should be behind an option. Please provide the ability restore the original operationality, honoring the entity names as per defined the database schema.

Request - Support for InterBase?

Hi, I would like to know if there is ever going to be any support for InterBase. The reason I ask, is because InterBase is using the Firebird ADO.NET derivers now. It seems like this should be an easy add on. Thanks.

Populating Fails with TimeOut

Here is the log Entry

6.11.11 (X64) 2021-04-20T12:44:25.9842861+05:00 Error opening DataContext
RemoteException - SqlException - Timeout expired.  The timeout period elapsed prior to completion of the operation or the server is not responding.
Source=Core .Net SqlClient Data Provider

 -System.Data.SqlClient.SqlConnection Void OnError(System.Data.SqlClient.SqlException, Boolean, System.Action`1[System.Action]) offset: 0x50
 -System.Data.SqlClient.SqlInternalConnection Void OnError(System.Data.SqlClient.SqlException, Boolean, System.Action`1[System.Action]) offset: 0x29
 -System.Data.SqlClient.TdsParser Void ThrowExceptionAndWarning(System.Data.SqlClient.TdsParserStateObject, Boolean, Boolean) offset: 0x157
 -System.Data.SqlClient.TdsParser Boolean TryRun(System.Data.SqlClient.RunBehavior, System.Data.SqlClient.SqlCommand, System.Data.SqlClient.SqlDataReader, System.Data.SqlClient.BulkCopySimpleResultSet, System.Data.SqlClient.TdsParserStateObject, Boolean ByRef) offset: 0x0
 -System.Data.SqlClient.SqlDataReader Boolean TryConsumeMetaData() offset: 0x40
 -System.Data.SqlClient.SqlDataReader System.Data.SqlClient._SqlMetaDataSet get_MetaData() offset: 0x31
 -System.Data.SqlClient.SqlCommand Void FinishExecuteReader(System.Data.SqlClient.SqlDataReader, System.Data.SqlClient.RunBehavior, System.String) offset: 0x92
 -System.Data.SqlClient.SqlCommand System.Data.SqlClient.SqlDataReader RunExecuteReaderTds(System.Data.CommandBehavior, System.Data.SqlClient.RunBehavior, Boolean, Boolean, Int32, System.Threading.Tasks.Task ByRef, Boolean, System.Data.SqlClient.SqlDataReader) offset: 0x33C
 -System.Data.SqlClient.SqlCommand System.Data.SqlClient.SqlDataReader RunExecuteReader(System.Data.CommandBehavior, System.Data.SqlClient.RunBehavior, Boolean, System.Threading.Tasks.TaskCompletionSource`1[System.Object], Int32, System.Threading.Tasks.Task ByRef, Boolean, System.String) offset: 0x79
 -System.Data.SqlClient.SqlCommand System.Data.SqlClient.SqlDataReader RunExecuteReader(System.Data.CommandBehavior, System.Data.SqlClient.RunBehavior, Boolean, System.String) offset: 0x0
 -System.Data.SqlClient.SqlCommand System.Data.SqlClient.SqlDataReader ExecuteReader(System.Data.CommandBehavior) offset: 0x2A
 -System.Data.SqlClient.SqlCommand System.Data.Common.DbDataReader ExecuteDbDataReader(System.Data.CommandBehavior) offset: 0x0
 -System.Data.Common.DbCommand System.Data.Common.DbDataReader ExecuteReader(System.Data.CommandBehavior) offset: 0x0
 -LinqToDB.Data.DbCommandProcessor.DbCommandProcessorExtensions System.Data.Common.DbDataReader ExecuteReaderExt(System.Data.IDbCommand, System.Data.CommandBehavior) offset: 0x19
 -LinqToDB.Data.DataConnection System.Data.IDataReader ExecuteReader(System.Data.IDbCommand, System.Data.CommandBehavior) offset: 0x0
 -LinqToDB.Data.DataConnection System.Data.IDataReader ExecuteReader(System.Data.CommandBehavior) offset: 0x96
 -LinqToDB.Data.CommandInfo System.Collections.Generic.IEnumerable`1[T] Query[T]() offset: 0x45
 -LinqToDB.Data.DataConnectionExtensions System.Collections.Generic.IEnumerable`1[T] Query[T](LinqToDB.Data.DataConnection, System.String) offset: 0x7
 -LinqToDB.LINQPad.LinqToDBDriver System.Nullable`1[System.DateTime] GetLastSchemaUpdate(LINQPad.Extensibility.DataContext.IConnectionInfo) offset: 0x2D


   INNER: Win32Exception - The wait operation timed out.
   
   (no stack trace)
Source=System.Private.CoreLib

 -System.Runtime.ExceptionServices.ExceptionDispatchInfo Void Throw() offset: 0x11
 -System.Runtime.CompilerServices.TaskAwaiter Void ThrowForNonSuccess(System.Threading.Tasks.Task) offset: 0x27
 -System.Runtime.CompilerServices.TaskAwaiter Void HandleNonSuccessAndDebuggerNotification(System.Threading.Tasks.Task) offset: 0x28
 -System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1+ConfiguredTaskAwaiter TResult GetResult() offset: 0xB
 -LINQPad.DataContextManager+<FetchDCInfoCore>d__31 Void MoveNext() offset: 0x30A


First Chance Data:
   -System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() offset=0x11

sproc parameter named ret error.

I think it is the same issue as in https://github.com/linq2db/t4models/issues/16
I've tried to connect to my database and got the following error:

System.Exception: (2029,11): error CS0136: A local or parameter named 'ret' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter

at LinqToDB.LINQPad.LinqToDBDriver.GetSchemaAndBuildAssembly(IConnectionInfo cxInfo, AssemblyName assemblyToBuild, String& nameSpace, String& typeName) in C:\projects\linq2db-linqpad\Source\LinqToDBDriver.cs:line 257
at LinqToDB.LINQPad.LinqToDBDriver.GetSchemaAndBuildAssembly(IConnectionInfo cxInfo, AssemblyName assemblyToBuild, String& nameSpace, String& typeName) in C:\projects\linq2db-linqpad\Source\LinqToDBDriver.cs:line 257

Support for Azure Cosmos DB

Its a feature request :) EF Core has a driver for Cosmos DB for few years now. It would be great to have this driver available in LinqPad. Cheers,

Incompatibility with a particular Microsoft Access Database.

I encountered the error message shown in the screenshot below when trying to add a connection to a particular Microsoft Access Database. The database file is attached in the Zip file below.

linqpad linq2db driver error message

At the "LINQ to DB Connection" dialog box, clicking on the Test button results in a successful test.

The accdb file opens fine in Microsoft Access 2013. LINQ2DB doesn't seem to have a problem in mapping out a database with no primary keys defined because I had a similarly structured Access Database that works great with LINQ2DB.

Note: I did not design the Access database. It's taken from a third-party software. So, I have no control over its design.

The LINQ2DB LINQPad driver that I'm using is of version 1.0.52 on LINQPad v5.22.02 .

Access Database.zip

Possibility to import existing templates

Is it possible to import existing classes that were made with the LinqToDB Templates?
I am asking, because the table and column names are adjusted in these classes.

Disable procedures and functions load by default

Right now it is enabled by default, which could be dangerous, as it leads to procedure execution in schema-only mode.
Usually it is safe, but for some databases combined with some specific procedure code it could lead to real execution (full or partial), so we should force user to accept risk explicitly.

No control over table name capitalization.

Tables and views in my databases often have names with specified capitalization, and previously the L2DB driver has left them intact. The new v5.0.0 driver however forces PascalCase on table and view names during refresh, with no apparent setting to disable this.

Example: View VDRMSite is generated as VdrmSite.

When testing code snippets or writing quick scripts the change in case for many of my table names wastes a ton of time as I have to search for the table in the tree view to find out what whacky name L2DB gave it.

Can we please get an option to use unmodified table names for class and property names where possible?

Error in GetSchemaAndBuildAssembly

When opening a connection I am getting the following exception.

image

I'm debugging from the latest Linq2DB.LINQPad master branch and this is just one of many exceptions but it is the only one that is displayed.

The line of generated code that this refers to is:

public ITable<@@__MigrationLog> @@__MigrationLogs { get { return this.GetTable<@@__MigrationLog>(); } }
This is connecting to an SQL Server database but I get similar issues when connecting to iSeries. A different SQL database doesn't give any issues but it only has a few tables and is very simple.

This is related to but different from #15

MysqlDriver retrieved the wrong count row

actually, the truth row is 13 but LinqPad always retrieved 10-row data. in the end, I try to delete one row, It is 12 rows, but that retrieved 10 rows again.
image
TheTestMysqlDataDemo.zip

MysqlDataBase info:
Server: MySQL (127.0.0.1 via TCP/IP)
Server type: MySQL
Server version: 5.7.30 - MySQL Community Server (GPL)
Protocol version: 10
User: root@localhost
Server charset: UTF-8 Unicode (utf8)

window 10 64bit Pro 21H1

Upgrade System.DirectoryServices.Protocols version

Hi

I setup linq2db.LINQPad 3.6.0, LINQPad will show a alert.

image

Warning: LINQPad has identified the following vulnerabilties in NuGet package System.DirectoryServices.Protocols 5.0.0:

Level 1 (Moderate): https://github.com/advisories/GHSA-9cxh-gqpx-qc5m
Try updating NuGet packages to latest. You can suppress this warning in Edit | Preferences > Advanced > Execution.

Adding MySQL broken

LP6/7, x86/x64.

Trying to add a MySql server.

  1. Pasted a correct connection string, pressed Test, got Successful!
  2. Pressed OK, the window got frozen, pressed the window close cross, got the standard Not Responding dialog, pressed Try to restore program, got

image

  1. Pressed Yes, got a message box with this:
---------------------------
Schema Build Error
---------------------------
System.MissingMethodException: Method not found: 'System.Collections.Immutable.ImmutableArray`1<Byte> System.Reflection.Metadata.MetadataReader.GetBlobContent(System.Reflection.Metadata.BlobHandle)'.

   at Microsoft.CodeAnalysis.MetadataReaderExtensions.CreateAssemblyIdentityOrThrow(MetadataReader reader, Version version, AssemblyFlags flags, BlobHandle publicKey, StringHandle name, StringHandle culture, Boolean isReference)

   at Microsoft.CodeAnalysis.MetadataReaderExtensions.ReadAssemblyIdentityOrThrow(MetadataReader reader) in /_/src/Compilers/Core/Portable/MetadataReader/MetadataReaderExtensions.cs:line 52

   at Microsoft.CodeAnalysis.PEAssembly..ctor(AssemblyMetadata owner, ImmutableArray`1 modules) in /_/src/Compilers/Core/Portable/MetadataReader/PEAssembly.cs:line 59

   at Microsoft.CodeAnalysis.AssemblyMetadata.GetOrCreateData() in /_/src/Compilers/Core/Portable/MetadataReference/AssemblyMetadata.cs:line 342

   at Microsoft.CodeAnalysis.AssemblyMetadata.GetModules() in /_/src/Compilers/Core/Portable/MetadataReference/AssemblyMetadata.cs:line 283

   at Microsoft.CodeAnalysis.AssemblyMetadata.IsValidAssembly() in /_/src/Compilers/Core/Portable/MetadataReference/AssemblyMetadata.cs:line 410

   at Microsoft.CodeAnalysis.CommonReferenceManager`2.GetMetadata(PortableExecutableReference peReference, CommonMessageProvider messageProvider, Location location, DiagnosticBag diagnostics) in /_/src/Compilers/Core/Portable/ReferenceManager/CommonReferenceManager.Resolution.cs:line 496

   at Microsoft.CodeAnalysis.CommonReferenceManager`2.ResolveMetadataReferences(TCompilation compilation, Dictionary`2 assemblyReferencesBySimpleName, ImmutableArray`1& references, IDictionary`2& boundReferenceDirectiveMap, ImmutableArray`1& boundReferenceDirectives, ImmutableArray`1& assemblies, ImmutableArray`1& modules, DiagnosticBag diagnostics) in /_/src/Compilers/Core/Portable/ReferenceManager/CommonReferenceManager.Resolution.cs:line 321

   at Microsoft.CodeAnalysis.CSharp.CSharpCompilation.ReferenceManager.CreateAndSetSourceAssemblyFullBind(CSharpCompilation compilation) in /_/src/Compilers/CSharp/Portable/Symbols/ReferenceManager.cs:line 357

   at Microsoft.CodeAnalysis.CSharp.CSharpCompilation.ReferenceManager.CreateSourceAssemblyForCompilation(CSharpCompilation compilation) in /_/src/Compilers/CSharp/Portable/Symbols/ReferenceManager.cs:line 184

   at Microsoft.CodeAnalysis.CSharp.CSharpCompilation.GetBoundReferenceManager() in /_/src/Compilers/CSharp/Portable/Compilation/CSharpCompilation.cs:line 1033

   at Microsoft.CodeAnalysis.CSharp.CSharpCompilation.get_SourceAssembly() in /_/src/Compilers/CSharp/Portable/Compilation/CSharpCompilation.cs:line 1257

   at Microsoft.CodeAnalysis.CSharp.CSharpCompilation.get_Assembly() in /_/src/Compilers/CSharp/Portable/Compilation/CSharpCompilation.cs:line 1270

   at Microsoft.CodeAnalysis.CSharp.CSharpCompilation.GetRuntimeMetadataVersion(EmitOptions emitOptions) in /_/src/Compilers/CSharp/Portable/Compilation/CSharpCompilation.cs:line 3394

   at Microsoft.CodeAnalysis.CSharp.CSharpCompilation.GetRuntimeMetadataVersion(EmitOptions emitOptions, DiagnosticBag diagnostics) in /_/src/Compilers/CSharp/Portable/Compilation/CSharpCompilation.cs:line 3376

   at Microsoft.CodeAnalysis.CSharp.CSharpCompilation.CreateModuleBuilder(EmitOptions emitOptions, IMethodSymbol debugEntryPoint, Stream sourceLinkStream, IEnumerable`1 embeddedTexts, IEnumerable`1 manifestResources, CompilationTestData testData, DiagnosticBag diagnostics, CancellationToken cancellationToken) in /_/src/Compilers/CSharp/Portable/Compilation/CSharpCompilation.cs:line 3121

   at Microsoft.CodeAnalysis.Compilation.CheckOptionsAndCreateModuleBuilder(DiagnosticBag diagnostics, IEnumerable`1 manifestResources, EmitOptions options, IMethodSymbol debugEntryPoint, Stream sourceLinkStream, IEnumerable`1 embeddedTexts, CompilationTestData testData, CancellationToken cancellationToken) in /_/src/Compilers/Core/Portable/Compilation/Compilation.cs:line 3062

   at Microsoft.CodeAnalysis.Compilation.Emit(Stream peStream, Stream metadataPEStream, Stream pdbStream, Stream xmlDocumentationStream, Stream win32Resources, IEnumerable`1 manifestResources, EmitOptions options, IMethodSymbol debugEntryPoint, Stream sourceLinkStream, IEnumerable`1 embeddedTexts, RebuildData rebuildData, CompilationTestData testData, CancellationToken cancellationToken) in /_/src/Compilers/Core/Portable/Compilation/Compilation.cs:line 2821

   at Microsoft.CodeAnalysis.Compilation.Emit(Stream peStream, Stream pdbStream, Stream xmlDocumentationStream, Stream win32Resources, IEnumerable`1 manifestResources, EmitOptions options, IMethodSymbol debugEntryPoint, Stream sourceLinkStream, IEnumerable`1 embeddedTexts, Stream metadataPEStream, RebuildData rebuildData, CancellationToken cancellationToken) in /_/src/Compilers/Core/Portable/Compilation/Compilation.cs:line 2778

   at LinqToDB.LINQPad.LinqToDBDriver.GetSchemaAndBuildAssembly(IConnectionInfo cxInfo, AssemblyName assemblyToBuild, String& nameSpace, String& typeName)
   at Microsoft.CodeAnalysis.MetadataReaderExtensions.CreateAssemblyIdentityOrThrow(MetadataReader reader, Version version, AssemblyFlags flags, BlobHandle publicKey, StringHandle name, StringHandle culture, Boolean isReference)

   at Microsoft.CodeAnalysis.MetadataReaderExtensions.ReadAssemblyIdentityOrThrow(MetadataReader reader) in /_/src/Compilers/Core/Portable/MetadataReader/MetadataReaderExtensions.cs:line 52

   at Microsoft.CodeAnalysis.PEAssembly..ctor(AssemblyMetadata owner, ImmutableArray`1 modules) in /_/src/Compilers/Core/Portable/MetadataReader/PEAssembly.cs:line 59

   at Microsoft.CodeAnalysis.AssemblyMetadata.GetOrCreateData() in /_/src/Compilers/Core/Portable/MetadataReference/AssemblyMetadata.cs:line 342

   at Microsoft.CodeAnalysis.AssemblyMetadata.GetModules() in /_/src/Compilers/Core/Portable/MetadataReference/AssemblyMetadata.cs:line 283

   at Microsoft.CodeAnalysis.AssemblyMetadata.IsValidAssembly() in /_/src/Compilers/Core/Portable/MetadataReference/AssemblyMetadata.cs:line 410

   at Microsoft.CodeAnalysis.CommonReferenceManager`2.GetMetadata(PortableExecutableReference peReference, CommonMessageProvider messageProvider, Location location, DiagnosticBag diagnostics) in /_/src/Compilers/Core/Portable/ReferenceManager/CommonReferenceManager.Resolution.cs:line 496

   at Microsoft.CodeAnalysis.CommonReferenceManager`2.ResolveMetadataReferences(TCompilation compilation, Dictionary`2 assemblyReferencesBySimpleName, ImmutableArray`1& references, IDictionary`2& boundReferenceDirectiveMap, ImmutableArray`1& boundReferenceDirectives, ImmutableArray`1& assemblies, ImmutableArray`1& modules, DiagnosticBag diagnostics) in /_/src/Compilers/Core/Portable/ReferenceManager/CommonReferenceManager.Resolution.cs:line 321

   at Microsoft.CodeAnalysis.CSharp.CSharpCompilation.ReferenceManager.CreateAndSetSourceAssemblyFullBind(CSharpCompilation compilation) in /_/src/Compilers/CSharp/Portable/Symbols/ReferenceManager.cs:line 357

   at Microsoft.CodeAnalysis.CSharp.CSharpCompilation.ReferenceManager.CreateSourceAssemblyForCompilation(CSharpCompilation compilation) in /_/src/Compilers/CSharp/Portable/Symbols/ReferenceManager.cs:line 184

   at Microsoft.CodeAnalysis.CSharp.CSharpCompilation.GetBoundReferenceManager() in /_/src/Compilers/CSharp/Portable/Compilation/CSharpCompilation.cs:line 1033

   at Microsoft.CodeAnalysis.CSharp.CSharpCompilation.get_SourceAssembly() in /_/src/Compilers/CSharp/Portable/Compilation/CSharpCompilation.cs:line 1257

   at Microsoft.CodeAnalysis.CSharp.CSharpCompilation.get_Assembly() in /_/src/Compilers/CSharp/Portable/Compilation/CSharpCompilation.cs:line 1270

   at Microsoft.CodeAnalysis.CSharp.CSharpCompilation.GetRuntimeMetadataVersion(EmitOptions emitOptions) in /_/src/Compilers/CSharp/Portable/Compilation/CSharpCompilation.cs:line 3394

   at Microsoft.CodeAnalysis.CSharp.CSharpCompilation.GetRuntimeMetadataVersion(EmitOptions emitOptions, DiagnosticBag diagnostics) in /_/src/Compilers/CSharp/Portable/Compilation/CSharpCompilation.cs:line 3376

   at Microsoft.CodeAnalysis.CSharp.CSharpCompilation.CreateModuleBuilder(EmitOptions emitOptions, IMethodSymbol debugEntryPoint, Stream sourceLinkStream, IEnumerable`1 embeddedTexts, IEnumerable`1 manifestResources, CompilationTestData testData, DiagnosticBag diagnostics, CancellationToken cancellationToken) in /_/src/Compilers/CSharp/Portable/Compilation/CSharpCompilation.cs:line 3121

   at Microsoft.CodeAnalysis.Compilation.CheckOptionsAndCreateModuleBuilder(DiagnosticBag diagnostics, IEnumerable`1 manifestResources, EmitOptions options, IMethodSymbol debugEntryPoint, Stream sourceLinkStream, IEnumerable`1 embeddedTexts, CompilationTestData testData, CancellationToken cancellationToken) in /_/src/Compilers/Core/Portable/Compilation/Compilation.cs:line 3062

   at Microsoft.CodeAnalysis.Compilation.Emit(Stream peStream, Stream metadataPEStream, Stream pdbStream, Stream xmlDocumentationStream, Stream win32Resources, IEnumerable`1 manifestResources, EmitOptions options, IMethodSymbol debugEntryPoint, Stream sourceLinkStream, IEnumerable`1 embeddedTexts, RebuildData rebuildData, CompilationTestData testData, CancellationToken cancellationToken) in /_/src/Compilers/Core/Portable/Compilation/Compilation.cs:line 2821

   at Microsoft.CodeAnalysis.Compilation.Emit(Stream peStream, Stream pdbStream, Stream xmlDocumentationStream, Stream win32Resources, IEnumerable`1 manifestResources, EmitOptions options, IMethodSymbol debugEntryPoint, Stream sourceLinkStream, IEnumerable`1 embeddedTexts, Stream metadataPEStream, RebuildData rebuildData, CancellationToken cancellationToken) in /_/src/Compilers/Core/Portable/Compilation/Compilation.cs:line 2778

   at LinqToDB.LINQPad.LinqToDBDriver.GetSchemaAndBuildAssembly(IConnectionInfo cxInfo, AssemblyName assemblyToBuild, String& nameSpace, String& typeName)
---------------------------
OK   
---------------------------
  1. Server added and seems working.

Error when reading Guid from Sql Azure.

I am trying to dump the results of a view, that view contains a column of type Guid ( sql type uniqueidentifier ) and so linqpad throws me this error:
image
I was inspecting the object and i was seeing that its sql type is as nvarchar(36) and the property type is string.

How can i set a custom mapping for this like its done in the Linq2Db, example.

SAP Sybase ASE broken

I am trying to connect to a Sybase database in Linqpad. After downloading the Linq to DB Connection driver, I choose SAP Sybase ASE as the data provider. I put in the connection string items, then try to connect. I am getting an error that says:
"Unable to find the requested .Net Framework Data Provider. It may not be installed"

Is anyone else able to connect to a sybase database using this driver? What can I do?

Unhandled error in method 'PreprocessObjectToWrite' for LINQPad8

LP8 - When the query is set to a linqpad connection, dumping any sequence of items will encounter the following error:

Unhandled error in method 'PreprocessObjectToWrite':
  The type initializer for 'LinqToDB.LlNQPad.ValueFormatter' threw an exception.
    at LinqToDB.LlNQPad.ValueFormatter.Format(Object value)
    at LinqToDB.LlNQPad.LinqToDBDriver.PreprocessObjectToWrite(Object& objectToWrite, ObjectGraphlnfo info)

LINQPad error appears with both versions 5.0.0 and 5.1.0 (for LINQPad versions 8.0.12 and 8.0.13).

Using SQL syntax when opening an SQLite DB

Hey friends,

I've been trying to use this driver on LINQPad and it works like a charm when using LINQ syntax.
However, when I use the SQL syntax, I get the following error message no matter which table I try to select:

"SQL logic error
no such table: X"
(X being the table I choose)

The schema is properly shown on the left-hand side menu, I made sure that I am using the correct connection, and I tried multiple .NET versions, all ends the same way.

When I right-click on the DB connection, the "Use in current query" button is grayed out, meaning it's already selected.

Screenshot:
image

Now, an interesting thing to add here, is that all of the above happens on a remote machine I am working with.

In my local PC it works perfectly, and to make matters even more confusing, if I just go ahead and copy the query from my local machine to the remote one, it works perfectly fine. If I type the whole thing from scratch, I'll get an issue again.
Even worse is that if I copy the query from the remote machine and run it on my local machine, I'll start having the issue on my side too.

Both machines are using English(United States) keyboards.

I tried to search the web for this error, but haven't found any posts that followed through.

Does anyone have any suggestions?

Thanks!
Eitan

Update target framework to 3.1

Latest version of LINQPad dropped today and all of my linq2db connections started blowing up. This might have been related to VS2019 installing .NET Core 3.0 target pack when I opened an older project.

Long story short, since linq2db.LINQPad targets .NET Core 3.0 LINQPad runs it under that framework. That works all the way up until the driver tries to load the linq2db assembly which requires .NET Core 3.1.

Can you please bump the target framework to netcoreapp3.1 and push a new version out to nuget? I don't want to have to go through purging .NET Core 3.0 every time I open an old project ๐Ÿ˜„

(I mean, I could build a custom version of the driver, but... yeah, nah)

LinqPad 6 support?

I renamed the lpx file to lpx6 but it failed to load.

Error instantiating type LinqToDB.LINQPad.LinqToDBStaticDriver in C:\Users\bea\AppData\Local\LINQPad\Drivers\DataContext\NetCore\linq2db.LINQPad\linq2db.LINQPad.dll
  - Driver assembly targets .NET Framework. Your driver assembly must target .NET Core 3.   at LINQPad.Extensibility.DataContext.DriverProxy.Instantiator.Instantiate(String assemblyPath, String typeName, String internalID)

Error instantiating type LinqToDB.LINQPad.LinqToDBDriver in C:\Users\bea\AppData\Local\LINQPad\Drivers\DataContext\NetCore\linq2db.LINQPad\linq2db.LINQPad.dll
  - Driver assembly targets .NET Framework. Your driver assembly must target .NET Core 3.   at LINQPad.Extensibility.DataContext.DriverProxy.Instantiator.Instantiate(String assemblyPath, String typeName, String internalID)

not thread safe?

Parallel.ForEach(rdbList, new ParallelOptions() { MaxDegreeOfParallelism = 4 }, (rdb, loopState) =>
{
	this.Insert(new test
			{
				Guid = guid,
				DataChange_LastTime = DateTime.Now,
			});
});

err:

Cannot set MySqlCommand.CommandText when there is an open DataReader for this command; it must be closed first.

LINQPad crash when connecting to Access (2003 - .mdb) database with linked tables

This seems to be an issue with linked tables, but I'm not actually getting an error just a crash.

I have one .mdb file that I split in two - one for the data and one for the rest. Linking to the non-data table causes LINQPad to crash outright. They both have security (the old workgroup kind, with a Security.mdw file), but I tried it without security and it still happened.

Linking to just the data table works fine, and makes more sense to do anyway, but just wanted to give you a heads up about the crash.

When I hit debug instead of close, I do get this in VS, if that helps:
Unhandled exception at 0x59B8E861 (msjetoledb40.dll) in LINQPad.exe: RangeChecks instrumentation code detected an out of range array access.

Can't close connection

Using the default LINQ to SQL driver for Sql Server, the Connection object in a LinqPad script starts out in a closed state and can be opened and closed as needed. But using the Linq2db driver (for a Postgres database), Connection starts out in an open state -- and it appears that calling Close() has no effect.

Connection.State.Dump();   // Open
Connection.Close();
Connection.State.Dump();   // Open

Is there a way to either get the connection to start closed, or to close it by hand?

Question - Connection settings for context from assembly

I'm trying to load a data context from an assembly using LinqPad6. In the dialog I am specifying an appsettings.json file but no matter what I enter, when I try to use the context I'm getting an exception that Configuration 'Default' is not defined.

What should the structure of the settings file be to configure this?

LinqPad6
Linq2DB LinqPad driver 3.1.0.0

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.