Giter Site home page Giter Site logo

linq2db / linq2db Goto Github PK

View Code? Open in Web Editor NEW
2.8K 149.0 450.0 491.69 MB

Linq to database provider.

License: MIT License

PLSQL 0.12% PLpgSQL 0.07% C# 98.81% F# 0.07% Batchfile 0.21% PowerShell 0.04% Visual Basic .NET 0.02% Shell 0.15% TSQL 0.44% Smalltalk 0.01% SQLPL 0.04% Python 0.04%
linq database orm sql access db2 firebird informix mysql postgresql

linq2db's People

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  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  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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

linq2db's Issues

Please provide a rough timeline ;)

I jsut got into trouble with BlToolkit yesterday again because of external references (making it for example unable to compile without warnings against cient framework). Really liking your work... Can you please provide a short timeline when linq2db will get usable code so that we can slowly start switching over? Thanks.

Postgres - InsertWithIndentity throws exception due to invalid sql

A postgres database often has multiple schemas.

When inserting data using linqtodb into a table with an auto-incrementing id, it correctly adds the schema to the sql.
(Note: I have tried with and without the SequenceName attribute on the id column)

nextval('schema1.table1_id_seq')

When trying to use InsertWithIdentity it fails due to not adding the schema:

SELECT currval('table1_id_seq')

Which causes you to get:
ERROR: relation "table1_id_seq" does not exist at character 16

Error with MiniProfiler

With BLToolkit I could do this:

var dbConnection = new SqlConnection("some connection string");
var connection = new StackExchange.Profiling.Data.ProfiledDbConnection(dbConnection, MiniProfiler.Current);
var manager = new Northwind(new SqlDataProvider(), connection);

where "Northwind" inherits from DbManager and SqlDataProvider is from BLToolkit.Data.DataProvider. This worked fine with BLToolkit. A similar approach with Linq2Db I'm guessing would be:

var dbConnection = new SqlConnection("some connection string");
var connection = new StackExchange.Profiling.Data.ProfiledDbConnection(dbConnection, MiniProfiler.Current);
var manager = new Northwind(new SqlServerDataProvider("???", SqlServerVersion.v2008), connection);

In this case Northwind inherits from DataConnection instead. However this code throws: Unable to cast object of type 'StackExchange.Profiling.Data.ProfiledDbDataReader' to type 'System.Data.SqlClient.SqlDataReader' when running a query. The exact same solution works with this DB initialization code:

var dbConnection = new SqlConnection("some connection string");
var manager = new Northwind(new SqlServerDataProvider("???", SqlServerVersion.v2008), dbConnection);

So, any way to use MiniProfiler the same way as with BLToolkit? Thanks.

LINQ to PostgreSql iTable Values Missing

When generating the PostgreSql class, looks like some ITable values were not generated: DeleteOnSubmit, DeleteAllOnSubmit, InsertAllOnSubmit, and InsertOnSubmit. Also, SubmitChanges was not generated.

I am not sure if that was a result of an error that occurred with the database I was generating from. I column name was named "string".

Find extension method

Is it possible to add Find extension method to quickly find an object by its id. It's annoying to write

var user = ctx.Users.Single(u=>u.UserId == userId);.

It would be nice to use

var user = ctx.Users.Find(userId);

instead.

Maria Db Issue on Mapping Columns

All columns are converted to Object using standard Mysql.data.dll data provider.

[Table("addresses")]
    public partial class address
    {
        [PrimaryKey, Identity   ] public object AddressID       { get; set; } // int(11)
        [Column,     NotNull    ] public object UserName        { get; set; } // varchar(50)
        [Column,     NotNull    ] public object FirstName       { get; set; } // varchar(50)
        [Column,     NotNull    ] public object LastName        { get; set; } // varchar(50)

More target frameworks

Hi, would be great if you could add more targeted frameworks in nuget package (new projects with separate build output), especially WinRT and then maybe portable target.

Generate sql "UPDATE TOP (N) ..." when Take(N) is called before Update()

It would be great if the following expression

db.GetTable<Test>()
    .Take(1)
    .Set(t => t.Name, "blah")
    .Update();

was translated into sql

UPDATE TOP(1) [Test] SET [Name] = 'blah'

Now it cause no exception at run-time, but is translated into

UPDATE [Test] SET [Name] = 'blah'

So it seems like Take(1) call is simply ignored.

The reason of this query is to update first record in DB that meets some condition no matter in what order - to my mind it perfectly matches the Take(N) semanticts. And BTW linq2db generates "SELECT TOP(1) ..." when Take is used in select expressions, so it makes a perfect sence to me to do the same thing in update.

Of course there is a workaround. For example:

db.GetTable<Test>()
    .Where(t => t.Id == db.GetTable<Test>()
        .Select(_ => _.Id)
        .First())
    .Set(t => t.Name, "blah")
    .Update();

But it is translated into a subselect

UPDATE [Table] [t]
SET [t].[Name] = 'blah'
WHERE [t].[Id] = (
    SELECT TOP (1) [_].[Id]
    FROM [Table] [_])

which may cause some issues, for example transaction deadlocks if pessimistic concurrency handling is used

PostgreSQL t4template - error while generating model

While generating my model I get the exception below.
PostgreSQL version: 9.1.9
Linq2db version: latest on NuGet (2013-09-04)
If you need the database schema I'll mail it to you.

Thanks!

Running transformation: Npgsql.NpgsqlException:
COALESCE types integer and character varying cannot be matched
Severity: ERROR
Code: 42804
at Npgsql.NpgsqlState.<ProcessBackendResponses_Ver_3>d__a.MoveNext()
at Npgsql.ForwardsOnlyDataReader.GetNextResponseObject()
at Npgsql.ForwardsOnlyDataReader.GetNextRowDescription()
at Npgsql.ForwardsOnlyDataReader.NextResult()
at Npgsql.ForwardsOnlyDataReader..ctor(IEnumerable1 dataEnumeration, CommandBehavior behavior, NpgsqlCommand command, NotificationThreadBlock threadBlock, Boolean synchOnReadError) at Npgsql.NpgsqlCommand.GetReader(CommandBehavior cb) at Npgsql.NpgsqlCommand.ExecuteReader(CommandBehavior cb) at Npgsql.NpgsqlCommand.ExecuteDbDataReader(CommandBehavior behavior) at System.Data.Common.DbCommand.System.Data.IDbCommand.ExecuteReader() at LinqToDB.Data.DataConnectionExtensions.<ExecuteQuery>d__151.MoveNext()
at System.Collections.Generic.List1..ctor(IEnumerable1 collection)
at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
at LinqToDB.DataProvider.PostgreSQL.PostgreSQLSchemaProvider.GetColumns(DataConnection dataConnection)
at LinqToDB.SchemaProvider.SchemaProviderBase.GetSchema(DataConnection dataConnection, GetSchemaOptions options)
at Microsoft.VisualStudio.TextTemplating72F48134C8263ADB28EB33BD7D54482CF961045C4A7F2BC27717A6D26645A91B6F7260B27D9356966483FF84BE1AD022A256D11928B2FB94103C5B03EA28B462.GeneratedTextTransformation.LoadServerMetadata(DataConnection dataConnection) in c:\workspace\TestLinq2DB\TestLinq2DB\LinqToDB.Templates\DataModel.ttinclude:line 47
at Microsoft.VisualStudio.TextTemplating72F48134C8263ADB28EB33BD7D54482CF961045C4A7F2BC27717A6D26645A91B6F7260B27D9356966483FF84BE1AD022A256D11928B2FB94103C5B03EA28B462.GeneratedTextTransformation.LoadMetadata(DataConnection dataConnection) in c:\workspace\TestLinq2DB\TestLinq2DB\LinqToDB.Templates\DataModel.ttinclude:line 251
at Microsoft.VisualStudio.TextTemplating72F48134C8263ADB28EB33BD7D54482CF961045C4A7F2BC27717A6D26645A91B6F7260B27D9356966483FF84BE1AD022A256D11928B2FB94103C5B03EA28B462.GeneratedTextTransformation.LoadPostgreSQLMetadata(String server, String port, String database, String uid, String password) in c:\workspace\TestLinq2DB\TestLinq2DB\LinqToDB.Templates\LinqToDB.PostgreSQL.ttinclude:line 55
at Microsoft.VisualStudio.TextTemplating72F48134C8263ADB28EB33BD7D54482CF961045C4A7F2BC27717A6D26645A91B6F7260B27D9356966483FF84BE1AD022A256D11928B2FB94103C5B03EA28B462.GeneratedTextTransformation.TransformText() in c:\workspace\TestLinq2DB\TestLinq2DB\Data\CopyMe.PostgreSQL.tt:line 37 c:\workspace\TestLinq2DB\TestLinq2DB\LinqToDB.Templates\DataModel.ttinclude 47 1 TestLinq2DB

1 to 1 mapping may be null

We referencing a back reference in a 1 to 1 association, the back reference record may not exist, so the join should be a left join, not an inner join. For example:

from p in cxt.Products
select new {
   p.ShoeDetail
}

Not all products have a ShoeDetail record (only shoes have a ShoeDetail record)

Bad SQL

For LINQ query:

from a in Assignments
                     where a.AssignmentsRelayAssignment.Relay_Id == 2
                           && a.AssignmentsRelayAssignment.Type == "Organizations"
                     select new Models.AssignmentGridItem
                     {
                         Id = a.Id,
                         DeliveryDate = a.DeliveryDate,
                         UndeliveryDate = a.UndeliveryDate,
                         WorksCount = a.WorksToAssignments.Count(),
                     };

generate SQL:

SELECT
    [a].[Id],
    [a].[DeliveryDate],
    [a].[UndeliveryDate],
    (
        SELECT
            Count(*)
        FROM
            [dbo].[Works] [c]
        WHERE
            [a].[Id] = [c].[Assignment_Id]
    ) as [c1]
FROM
    [dbo].[Assignments] [a]
        INNER JOIN [dbo].[AssignmentsRelay] [t1] ON [a].[Id] = [t1].[Id]
        INNER JOIN [dbo].[Works] [t2] ON [a].[Id] = [t2].[Assignment_Id]
WHERE
    [t1].[Relay_Id] = 2 AND [t1].[Type] = 'Organizations'

Join to Works table not need

why not use doubles instead of floats? (losing precision on Lat/Lon coordinate values)

Hi, I've been trying to write my app using linq2db, I've noticed a quirk regarding REAL fields, being converted to floats on the generated data model. This can be easily avoided by doing a replace all "float" to "double" over the data model file. However, I was wondering if this is a wanted behavior, and if not, let you know about it.

Thanks.
Marcelo.

Safe to use?

For new projects would you recommend we stick with BLT or use L2DB instead? Are you planning any major breaking changes for L2DB? Thanks.

Project files not compatible with VS 2010

I opened the solution in VS 2010 and all the Test projects, Linq2Db and Linq2Dd.WindowsStore projects are not loaded because of different project file format.

Please make the project type compatible with VS 2010.

T4 models, and duplicate column names

When something procedure exist like this:

create procedure x_duplicate_column_names
as
begin
select 123 as id, 456 as id
end
go

Then T4 generation fails with:

Error   3   Running transformation: System.ArgumentException: An item with the same key has already been added.
   at System.ThrowHelper.ThrowArgumentException(ExceptionResource resource)
   at System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add)
   at System.Linq.Enumerable.ToDictionary[TSource,TKey,TElement](IEnumerable`1 source, Func`2 keySelector, Func`2 elementSelector, IEqualityComparer`1 comparer)
   at System.Linq.Enumerable.ToDictionary[TSource,TKey,TElement](IEnumerable`1 source, Func`2 keySelector, Func`2 elementSelector)
   at Microsoft.VisualStudio.TextTemplating7606E008372CBD07E42BCB71F2E0930EAFAD676B6CB295DF3B48E4D99343F06D2126B620E6CB982286C5F3122455E1AC418527400FAA7DA54956DE6360AB3E5C.GeneratedTextTransformation.<>c__DisplayClass46.<LoadServerMetadata>b__3d(ProcedureSchema p) in d:\prj\!temp\Linq2DbPlayground\Linq2DbPlayground\LinqToDB.Templates\DataModel.ttinclude:line 138
   at System.Linq.Enumerable.WhereSelectListIterator`2.MoveNext()
   at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
   at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
   at Microsoft.VisualStudio.TextTemplating7606E008372CBD07E42BCB71F2E0930EAFAD676B6CB295DF3B48E4D99343F06D2126B620E6CB982286C5F3122455E1AC418527400FAA7DA54956DE6360AB3E5C.GeneratedTextTransformation.LoadServerMetadata(DataConnection dataConnection) in d:\prj\!temp\Linq2DbPlayground\Linq2DbPlayground\LinqToDB.Templates\DataModel.ttinclude:line 137
   at Microsoft.VisualStudio.TextTemplating7606E008372CBD07E42BCB71F2E0930EAFAD676B6CB295DF3B48E4D99343F06D2126B620E6CB982286C5F3122455E1AC418527400FAA7DA54956DE6360AB3E5C.GeneratedTextTransformation.LoadMetadata(DataConnection dataConnection) in d:\prj\!temp\Linq2DbPlayground\Linq2DbPlayground\LinqToDB.Templates\DataModel.ttinclude:line 218
   at Microsoft.VisualStudio.TextTemplating7606E008372CBD07E42BCB71F2E0930EAFAD676B6CB295DF3B48E4D99343F06D2126B620E6CB982286C5F3122455E1AC418527400FAA7DA54956DE6360AB3E5C.GeneratedTextTransformation.TransformText() in d:\prj\!temp\Linq2DbPlayground\Linq2DbPlayground\DataContext.tt:line 45  d:\prj\!temp\Linq2DbPlayground\Linq2DbPlayground\LinqToDB.Templates\DataModel.ttinclude 138 1   Linq2DbPlayground

It is looks like happens near-by (procedures selection):

                        Columns  = p.ResultTable.Columns.ToDictionary(
                            c => c.ColumnName,
                            c => new Column
                            {

SAP Hana Integration... welcome?

I am in the process of evaluating Linq2Db for the use at a customer's Project. It happens the proejct is using SAP Hana as database, which - while utilizing ODBC as Connection technoloy - like always Comes with it's own simple variations of the SQL Syntax.

Would it be of interest to submit the Hana DataProvider? Or shall I Keep it to myself?

Association truble

If association property used in select clause, query crash.

Query:

var db = new DataConnection();
var res = 
    from o in db.GetTable<Organization>() 
    where o.Id == 1 
    select new Class1<Organization, IEnumerable<Employee>>() { obj = o, Expand = o.EmployesToOrganizations };
var arr = res.ToArray();

Object model.

public class Organization
{
  [PrimaryKey, Identity ] 
  public int    Id  { get; set; } 

  [Column, Nullable] 
  public string Name { get; set; }

  [Association(ThisKey="Id", OtherKey="Organization_Id", CanBeNull=false)]
  public IEnumerable<Employee> EmployesToOrganizations { set; set; }
}
public class Employee
{
  [PrimaryKey, Identity ] 
  public int    Id  { get; set; } 

  [Column]
  public string FIO { get; set; }

  [Column, NotNull]
  public int Organization_Id { get; set; }
}
class Class1<T, TExpand>
    {
        public T obj { get; set; }
        public TExpand Expand { get; set; }
    }

Member is not a table column.

В модели кода тип Status - enum, где к каждому члену привязано идентифицирующее число.
В БД: [Status] TINYINT NOT NULL
В BLToolkit работало.

[LinqException: Member 'DatabasePicture.Status' is not a table column.]
LinqToDB.Linq.Builder.TableContext.GetField(Expression expression, Int32 level, Boolean throwException) +2226
LinqToDB.Linq.Builder.TableContext.FindTable(Expression expression, Int32 level, Boolean throwException) +95
LinqToDB.Linq.Builder.TableContext.ConvertToSql(Expression expression, Int32 level, ConvertFlags flags) +584
LinqToDB.Linq.Builder.ExpressionContext.ConvertToSql(Expression expression, Int32 level, ConvertFlags flags) +125
LinqToDB.Linq.Builder.ExpressionBuilder.ConvertToSql(IBuildContext context, Expression expression, Boolean unwrap) +3948
LinqToDB.Linq.Builder.ExpressionBuilder.ConvertEnumConversion(IBuildContext context, Expression left, Operator op, Expression right) +882
LinqToDB.Linq.Builder.ExpressionBuilder.ConvertCompare(IBuildContext context, ExpressionType nodeType, Expression left, Expression right) +645
LinqToDB.Linq.Builder.ExpressionBuilder.ConvertPredicate(IBuildContext context, Expression expression) +170
LinqToDB.Linq.Builder.ExpressionBuilder.BuildSearchCondition(IBuildContext context, Expression expression, List1 conditions) +625 LinqToDB.Linq.Builder.ExpressionBuilder.ConvertToSql(IBuildContext context, Expression expression, Boolean unwrap) +238 LinqToDB.Linq.Builder.ExpressionBuilder.ConvertToSql(IBuildContext context, Expression expression, Boolean unwrap) +5125 LinqToDB.Linq.Builder.ExpressionBuilder.ConvertPredicate(IBuildContext context, Expression expression) +2027 LinqToDB.Linq.Builder.ExpressionBuilder.BuildSearchCondition(IBuildContext context, Expression expression, List1 conditions) +625
LinqToDB.Linq.Builder.ExpressionBuilder.BuildSearchCondition(IBuildContext context, Expression expression, List1 conditions) +289 LinqToDB.Linq.Builder.ExpressionBuilder.ConvertToSql(IBuildContext context, Expression expression, Boolean unwrap) +238 LinqToDB.Linq.Builder.ExpressionBuilder.ConvertToSql(IBuildContext context, Expression expression, Boolean unwrap) +5125 LinqToDB.Linq.Builder.ExpressionBuilder.ConvertPredicate(IBuildContext context, Expression expression) +2027 LinqToDB.Linq.Builder.ExpressionBuilder.BuildSearchCondition(IBuildContext context, Expression expression, List1 conditions) +625
LinqToDB.Linq.Builder.ExpressionBuilder.BuildSearchCondition(IBuildContext context, Expression expression, List1 conditions) +117 LinqToDB.Linq.Builder.ExpressionBuilder.BuildSearchCondition(IBuildContext context, Expression expression, List1 conditions) +101
LinqToDB.Linq.Builder.ExpressionBuilder.BuildWhere(IBuildContext parent, IBuildContext sequence, LambdaExpression condition, Boolean checkForSubQuery) +246
LinqToDB.Linq.Builder.WhereBuilder.BuildMethodCall(ExpressionBuilder builder, MethodCallExpression methodCall, BuildInfo buildInfo) +180
LinqToDB.Linq.Builder.MethodCallBuilder.BuildSequence(ExpressionBuilder builder, BuildInfo buildInfo) +55
LinqToDB.Linq.Builder.ExpressionBuilder.BuildSequence(BuildInfo buildInfo) +201
LinqToDB.Linq.Builder.OrderByBuilder.BuildMethodCall(ExpressionBuilder builder, MethodCallExpression methodCall, BuildInfo buildInfo) +105
LinqToDB.Linq.Builder.MethodCallBuilder.BuildSequence(ExpressionBuilder builder, BuildInfo buildInfo) +55
LinqToDB.Linq.Builder.ExpressionBuilder.BuildSequence(BuildInfo buildInfo) +201
LinqToDB.Linq.Builder.OrderByBuilder.BuildMethodCall(ExpressionBuilder builder, MethodCallExpression methodCall, BuildInfo buildInfo) +105
LinqToDB.Linq.Builder.MethodCallBuilder.BuildSequence(ExpressionBuilder builder, BuildInfo buildInfo) +55
LinqToDB.Linq.Builder.ExpressionBuilder.BuildSequence(BuildInfo buildInfo) +201
LinqToDB.Linq.Builder.SelectBuilder.BuildMethodCall(ExpressionBuilder builder, MethodCallExpression methodCall, BuildInfo buildInfo) +175
LinqToDB.Linq.Builder.MethodCallBuilder.BuildSequence(ExpressionBuilder builder, BuildInfo buildInfo) +55
LinqToDB.Linq.Builder.ExpressionBuilder.BuildSequence(BuildInfo buildInfo) +201
LinqToDB.Linq.Builder.CountBuilder.BuildMethodCall(ExpressionBuilder builder, MethodCallExpression methodCall, BuildInfo buildInfo) +121
LinqToDB.Linq.Builder.MethodCallBuilder.BuildSequence(ExpressionBuilder builder, BuildInfo buildInfo) +55
LinqToDB.Linq.Builder.ExpressionBuilder.BuildSequence(BuildInfo buildInfo) +201
LinqToDB.Linq.Builder.ExpressionBuilder.Build() +100
LinqToDB.Linq.Query1.GetQuery(IDataContextInfo dataContextInfo, Expression expr) +346 LinqToDB.Linq.ExpressionQuery1.GetQuery(Expression expression, Boolean cache) +69
LinqToDB.Linq.ExpressionQuery1.System.Linq.IQueryProvider.Execute(Expression expression) +20 System.Linq.Queryable.Count(IQueryable1 source) +233

Association Documentation

Hi, this is not a bug.
I dont find examples to use Association.

I use te Chinook database, tt generates:

    [Table(Schema="dbo", Name="Album")]
    public partial class Album
    {
        [PrimaryKey, Identity] public int    AlbumId  { get; set; } // int
        [Column,     NotNull ] public string Title    { get; set; } // nvarchar(160)
        [Column,     NotNull ] public int    ArtistId { get; set; } // int

        #region Associations

        /// <summary>
        /// FK_AlbumArtistId
        /// </summary>
        [Association(ThisKey="ArtistId", OtherKey="ArtistId", CanBeNull=false)]
        public Artist AlbumArtistId { get; set; }

        /// <summary>
        /// FK_TrackAlbumId_BackReference
        /// </summary>
        [Association(ThisKey="AlbumId", OtherKey="AlbumId", CanBeNull=false)]
        public IEnumerable<Track> TrackAlbumIds { get; set; }

        #endregion
    }

    [Table(Schema="dbo", Name="Artist")]
    public partial class Artist
    {
        [PrimaryKey, Identity] public int    ArtistId { get; set; } // int
        [Column,     Nullable] public string Name     { get; set; } // nvarchar(120)

        #region Associations

        /// <summary>
        /// FK_AlbumArtistId_BackReference
        /// </summary>
        [Association(ThisKey="ArtistId", OtherKey="ArtistId", CanBeNull=false)]
        public IEnumerable<Album> AlbumArtistIds { get; set; }

        #endregion
    }

My Code on the form:

        private void Form1_Load(object sender, EventArgs e)
        {
            using (var db = new Modelos.ChinookDB())
            {
                var q =
                    from c in db.Albums
                    select c;

                gvAlbums.DataSource = q.ToList();
            }
        }

        private void gvAlbums_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            var album = gvDatos.Rows[e.RowIndex].DataBoundItem as Modelos.Album;

            if (album != null)
            {
                //TrackAlbumIds is null
                gvTracks.DataSource = album.TrackAlbumIds.ToList();

                /* Works
                using (var db = new Modelos.ChinookDB())
                {
                    var q =
                        from c in db.Tracks
                        where c.AlbumId == album.AlbumId
                        orderby c.TrackId
                        select c;

                    gvTracks.DataSource = q.ToList();
                }
                */
            }
        }

but this dont work, album.TrackAlbumIds is null.

what is the correct mode?

Create support for wrapping connection object to MiniProfiler

Typically in most of the MicroORM we have access to the DBConnection, so it is very easy to wrap them with the MiniProfiler. Since the DBConnection is a readonly property, please create a mechanism to to wrap the connection object to MiniProfiler. It would nice if you can create a factory method like that of the implementation in Siso-DB - https://github.com/danielwertheim/SisoDb-Provider/tree/master/Source/Projects/SisoDb.MiniProfiler

byte[] colum - System.NotImplementedException: The method or operation is not implemented.

Hi,
first of all - great lib :)

I'm getting error, when one of table column is byte[] if no byte[] type is used, then it works fine. I'm using linq2db SqlCe 4 provider and error is on Insert method. Error details:

System.NotImplementedException: The method or operation is not implemented.
LinqToDB.Linq.Builder.ExpressionContext.ConvertToSql(Expression expression, Int32 level, ConvertFlags flags)
LinqToDB.Linq.Builder.UpdateBuilder.BuildSetter(ExpressionBuilder builder, BuildInfo buildInfo, LambdaExpression setter, IBuildContext into, List1 items, IBuildContext sequence) LinqToDB.Linq.Builder.InsertBuilder.BuildMethodCall(ExpressionBuilder builder, MethodCallExpression methodCall, BuildInfo buildInfo) LinqToDB.Linq.Builder.MethodCallBuilder.BuildSequence(ExpressionBuilder builder, BuildInfo buildInfo) LinqToDB.Linq.Builder.ExpressionBuilder.BuildSequence(BuildInfo buildInfo) LinqToDB.Linq.Builder.ExpressionBuilder.Build[T]() LinqToDB.Linq.Query1.GetQuery(IDataContextInfo dataContextInfo, Expression expr)
LinqToDB.Linq.ExpressionQuery1.GetQuery(Expression expression, Boolean cache) LinqToDB.Linq.ExpressionQuery1.System.Linq.IQueryProvider.Execute[TResult](Expression expression)
LinqToDB.LinqExtensions.Insert[T](ITable1 target, Expression1 setter)

Executing LINQ query after stored procedure call

When in one DataConnection i'm execute stored procedure and then execute LINQ query it is failed with exception like 'Stored procedure '' not found.'.
This is happens, 'cause Command object reused, and CommandType is not set to CommandType.Text when executing query.

I.e. i'm quickfix tis forself with, but may be other way exist:

// DataConnection.cs

public void SetCommand(string sql)
{
    DataProvider.InitCommand(this);
    Command.CommandText = LastQuery = sql;
    Command.CommandType = CommandType.Text;   // !!! my addition
}

(I'm just remember this problem, so describe this by memory).

t4models: generating data context only for stored procedures

Once we remove any tables before GenerateModel():

    LoadMetadata(dataConnection);
    Tables.Clear();
    GenerateModel();

It doesn't generate SP wrappers.

This is happens 'cause GenerateTypesFromMetadata immediate returns:

void GenerateTypesFromMetadata()
{
    if (Tables.Count == 0)
        return;

I.e. probably it is must check also procedures count:

    if (Tables.Count == 0 && Procedures.Count == 0)

PS: Sorry for spamming, currently can't make any pull request.

Init DataConnection without config

When initializing a DataConnection to be used with MiniProfiler I have to wrap the SqlConnection in MiniProfiler's connection. Right now, to do this I have to have a (factory) method that sets all this up. This works, but with a few tweaks I could do all that from the constructor. Here's what I'd like to do:

  public class Db : DataConnection
  {
#if !DEBUG
    public Db() : base("xyz")
    {

    }
#else
    public Db()
    {
      LinqToDB.Common.Configuration.AvoidSpecificDataProviderAPI = true;

      ConnectionString = @"Server=.\SQL2008;Database=Northwind;Trusted_Connection=True;Enlist=False;";
      var dbConnection = new SqlConnection(ConnectionString);
      Connection = new StackExchange.Profiling.Data.ProfiledDbConnection(dbConnection, MiniProfiler.Current);

      DataProvider = new SqlServerDataProvider("", SqlServerVersion.v2008);
    }
#endif
  }

The problem is that the setters for ConnectionString are DataProvider are private. If these could be change to protected then it would work. Also, Connection does not have a setter, so it'd need: protected set { _connection = value; }. With these three changes the code above works in my tests.

I don't know if bypassing the initialization code from constructors would have any side effects; it worked fine for me. Alternately, there could a protected method that I could call that would handle the internal initialization.

I noticed that all the constructors try to read from the configuration. Since I already store that configuration in a different object, it would be nice to be able to create DataConnection objects without the .config dependency.

Thanks,
Peter

P.S. DataProviderBase should throw an exception if the "name" parameter is null. It is used in many places where it assumes it's not null.

Introduce GetSchema() options (get / ignore SP's / progress / predefined SP set)

It will be cool if GetSchema() behavior can be customized:

  • is disable to discover SP's schemas;
  • define which exact SP's need to be processed;
  • notify about progress.

Why?

For example one of my production database contains relatively many tables and about 10000 SP's. Usually i'm really need only very limited set of known SP's and and not all tables.
Many tables doesn't get too many problems, 'cause they processed relatively fast.
But grabbing schemas over 10000 SP's get about 8 minutes. In this case also may be good to have any progress information...

It is just as idea, feature request. I mean low level. :)

PS: Good library, good new API. DataParameter now doesn't confict with C#'s enum implicit casting, and it is good. Thanks, for hard work!

Startup Performance Enquiry

First, congratulations on a great frameowork.

I'm interested in startup performance of LinqToDB. Should I be worried about the startup performance in case of a schema with many tables?

My initial tests show that linq2db starts much faster comparing to EF for a big schema, however for a smaller schema both frameworks introduce startup delay around 300 ms, which is tolerable.

How does startup performance compares to micro-frameworks? Is there a any background compilation step included?

Thanks,
Marko

Longer intro / README

BLToolkit and Linq2DB are excellent tools, far less popular than they deserve. I would like to help with that by writing a longer, more descriptive introduction / tutorial similar to Massive and Dapper's GitHub page. Let me know if you would accept such a pull request and if you have any guidelines for the introduction. Thanks for your hard work!

Configuration string not provided in DB2

I have set up my project following the instructions provided but when I run a test I get an Exception with the Message "Configuration string not provided." when I call var db = new SftwMgmtDB().

This is what My app config looks like with the Myserver ,UID, and PWD replace with my server info.

Any help would be appreciated

MYSQL Provide retriving Object info form more than one object

I have two Schema available in my database. When I have only table in my schema and other schema has table and views both. TT file is including tables form my schema and views form other schema to the generated class. I created a sample view in my schema and now there is an error as below..

Error 1 Running transformation: System.ArgumentException: An item with the same key has already been added.
at System.ThrowHelper.ThrowArgumentException(ExceptionResource resource)
at System.Collections.Generic.Dictionary2.Insert(TKey key, TValue value, Boolean add) at System.Linq.Enumerable.ToDictionary[TSource,TKey,TElement](IEnumerable1 source, Func2 keySelector, Func2 elementSelector, IEqualityComparer1 comparer) at System.Linq.Enumerable.ToDictionary[TSource,TKey,TElement](IEnumerable1 source, Func2 keySelector, Func2 elementSelector)
at Microsoft.VisualStudio.TextTemplatingB4B1BD36D8117662FB5EEF8D2F36BEF6E644100D28E2FCA4620422B8D5BC2A206FD20E8EC9E1B6126AF9F5EE94C5E5CC24CA10DC32B9D963EAEA67619CA49D2B.GeneratedTextTransformation.b__45(TableSchema t) in c:\Chandra\Projects\MauryaSystems\Web\trunk\Project\Source\MRS.Web\MSys.DBHelper\LinqToDB.Templates\DataModel.ttinclude:line 70
at System.Linq.Enumerable.WhereSelectListIterator2.MoveNext() at System.Collections.Generic.List1..ctor(IEnumerable1 collection) at System.Linq.Enumerable.ToList[TSource](IEnumerable1 source)
at Microsoft.VisualStudio.TextTemplatingB4B1BD36D8117662FB5EEF8D2F36BEF6E644100D28E2FCA4620422B8D5BC2A206FD20E8EC9E1B6126AF9F5EE94C5E5CC24CA10DC32B9D963EAEA67619CA49D2B.GeneratedTextTransformation.LoadServerMetadata(DataConnection dataConnection) in c:\Chandra\Projects\MauryaSystems\Web\trunk\Project\Source\MRS.Web\MSys.DBHelper\LinqToDB.Templates\DataModel.ttinclude:line 69
at Microsoft.VisualStudio.TextTemplatingB4B1BD36D8117662FB5EEF8D2F36BEF6E644100D28E2FCA4620422B8D5BC2A206FD20E8EC9E1B6126AF9F5EE94C5E5CC24CA10DC32B9D963EAEA67619CA49D2B.GeneratedTextTransformation.LoadMetadata(DataConnection dataConnection) in c:\Chandra\Projects\MauryaSystems\Web\trunk\Project\Source\MRS.Web\MSys.DBHelper\LinqToDB.Templates\DataModel.ttinclude:line 259
at Microsoft.VisualStudio.TextTemplatingB4B1BD36D8117662FB5EEF8D2F36BEF6E644100D28E2FCA4620422B8D5BC2A206FD20E8EC9E1B6126AF9F5EE94C5E5CC24CA10DC32B9D963EAEA67619CA49D2B.GeneratedTextTransformation.LoadMySqlMetadata(String server, String database, String uid, String password) in c:\Chandra\Projects\MauryaSystems\Web\trunk\Project\Source\MRS.Web\MSys.DBHelper\LinqToDB.Templates\LinqToDB.MySql.ttinclude:line 28
at Microsoft.VisualStudio.TextTemplatingB4B1BD36D8117662FB5EEF8D2F36BEF6E644100D28E2FCA4620422B8D5BC2A206FD20E8EC9E1B6126AF9F5EE94C5E5CC24CA10DC32B9D963EAEA67619CA49D2B.GeneratedTextTransformation.TransformText() in c:\Chandra\Projects\MauryaSystems\Web\trunk\Project\Source\MRS.Web\MSys.DBHelper\DataModel\MSysDBModel.tt:line 37 c:\Chandra\Projects\MauryaSystems\Web\trunk\Project\Source\MRS.Web\MSys.DBHelper\LinqToDB.Templates\DataModel.ttinclude 70 1 MSys.DBHelper

Not mapped property

Query crash if entity contains property not mapped DB and not declared attributes.
Example:

class test{
[Column]
public  string mapped{get;set;}

public string NotMapped{get;set;}
}

Ability to use Linq2db in Onion architecture

If possible can you split the main project into two parts ? One with the helper/utility classes and the annotation classes and the other with the DB stuff ? This will help in putting the utility/annotation class assembly in non DAL layer projects and the DB part of Linq2DB in the DAL layer project.

FluentMappingBuilder Different Mappings for same Type

I've different classes in wich are some Properties, wich are List.

Now I have used BLToolkit before, and there I could specify MemberMeppers for each property.

Now I want to switch to Linq2Db. The Problem is, sometimes i hav to use a CSVSerialisationMapper and Somtimes a XMLSerialisationMapper for the List

Is this possible in any way? At the Moment I only see, I can specify it for a type, and not a Name:

mappingSchema.SetConverter<MyType,byte[]>(value => ConvertMyTypeToByteArray(value));
mappingSchema.SetConverter<byte[],MyType>(value => ConvertByteArrayToMyType(value));

Недоступные методы и классы

Пытался перенести код библиотеки для работы с WCF Data service 5.3

под linq2db. Возникло две проблемы:

  1. Класс EntityDescriptor и метод MappingSchema.GetEntityDescriptor не доступны др. библиотекам (помечены internal)

  2. В BLT я использовал для получения первичного ключа такой код:

    var sqlTable = new SqlTable();
    var pkField = sqlTable.Fields.Values.First(f => f.IsPrimaryKey);
    var pkValue = pkField.MemberMapper.GetValue(Resource);

Но в l2db нет для SqlField свойства MemberMapper.

T4 models and empty column names

Create procedure:

create procedure x_select_implicit_column
as
begin
select 123
end
go

In this case T4 models generates wrong next output:

#region x_select_implicit_column

public partial class x_select_implicit_columnResult
{
    public int  { get; set; }
}

public static IEnumerable<x_select_implicit_columnResult> x_select_implicit_column(this DataConnection dataConnection)
{
    return dataConnection.QueryProc<x_select_implicit_columnResult>("[x_select_implicit_column]");
}

#endregion

UPD: Of course there can be many column names without names (generate new names?). It is hard to diagnose (without knowledge of procedure for which failed generation). It is just from existing production database.

SQLite.Interop.dll And System.Data.SQLite.dll old versions support.

Hello. First let me thank you for your responsiveness and all the good work you are doing over linq2db.

I was experimenting with linq2db a little more, trying to adapt it to our project and not the other way around.
We happen to be using an old version of System.Data.SQLite.dll (1.0.82.0) to target old frameworks.

  • Is there a particular reason linq2db (Linq To SQLite flavor ) is shipped with the newest version of System.Data.SQLite.dll (1.0.86.0)? it seems to work so far with the old one (82), and I'm hesitant to switching to an older version of linq2db since I cannot find any change log for linq2db to see what has been fixed/added in newer versions.
  • If there's a change log for lin2db / Linq To SQLite could you point me to it?
  • If this isn't the right place for this questions please tell me so I don't flood your issues tracker with my questions :)

Best regards.
Marcelo.

Field property

Not an issue, but a suggestion: Working with BLToolkit I find myself having more properties with MapIgnore that actual DB fields. I would suggest a way to tag the DB fields, instead of tagging every other property with MapIgnore. If it doesn't add too much complexity there could even be a switch somewhere in DbManager. Thanks for your consideration and work on BLToolkit.

Interface to log sql and its timing

Is it possible to add an interface to log the sql and its execution time separately ? I have made an attempt to add the ability to log sqls using a separate function in the places where you are using TraceSwitch. You can look at the my changes @

gkathire@260598a

GetSchema() can fail without sensitive information

Let's explain issue step by step:

We have some SP like this. I.e. it is inserts in temp table something, but not actuall creates it.

create procedure linq2db_test_insertIntoTempTable
as

    insert into #TempTable (Id, Name)
    select x.Id, x.Name from (
        select  1 as Id, 'A' as Name union all
        select  2, 'B'
    ) x
go

Now we try get schema, and got exception:

System.Data.SqlClient.SqlException (0x80131904): Invalid object name '#TempTable'.
   at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
   at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
   at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
   at System.Data.SqlClient.SqlDataReader.TryConsumeMetaData()
   at System.Data.SqlClient.SqlDataReader.get_MetaData()
   at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString)
   at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite)
   at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite)
   at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method)
   at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method)
   at System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior)
   at System.Data.Common.DbCommand.System.Data.IDbCommand.ExecuteReader(CommandBehavior behavior)
   at LinqToDB.Data.DataConnectionExtensions.ExecuteReader(DataConnection connection, String sql, CommandType commandType, CommandBehavior commandBehavior, DataParameter[] parameters) in d:\prj\!temp\linq2db-master\Source\Data\DataConnectionExtensions.cs:line 298
   at LinqToDB.DataProvider.SqlServer.SqlServerSchemaProvider.GetSchema(DataConnection dataConnection) in d:\prj\!temp\linq2db-master\Source\DataProvider\SqlServer\SqlServerSchemaProvider.cs:line 365
   at Linq2DbPlayground.Program.Main(String[] args) in d:\prj\!temp\Linq2DbPlayground\Linq2DbPlayground\Program.cs:line 24
ClientConnectionId:104abdf5-155c-44a7-8cd5-0894af6dfb7d

Note that procedure must be never called (i.e. probably plan / schema for they never be cached by mssql).
And #TempTable also not exist.

So main problem - that exception info are non informative (i.e. it is doesn't contain name of SP which failed).

And if problem like this occurs - this is prevent to generate schema for tables only for example from t4models...

So probably will be good:

  1. Make exception more informative (include command text for which can't be obtained schema info).
  2. Optionally ignore errors like this.

Bad SQL

For query:

this.GetTable<Departament>().Where(it => IIF((IIF((it.Name == null), null, Convert(it.Name.StartsWith("КИ"))) == null), False, IIF((it.Name == null), null, Convert(it.Name.StartsWith("КИ"))).Value))

result SQL:

SELECT
    [it].[Name],
    [it].[Type] as [Type1],
    [it].[Chief_Id],
    [it].[Parent_Id],
    [it].[Id]
FROM
    [Departaments] [it]
WHERE
    CASE
        WHEN CASE
            WHEN [it].[Name] IS NULL THEN NULL
            ELSE [it].[Name] LIKE N'КИ%'
        END IS NULL
            THEN 0
        WHEN [it].[Name] IS NULL THEN NULL
        ELSE [it].[Name] LIKE N'КИ%'
    END = 1

This query build WCF Data Services for uri: http://localhost:50089/ricService.svc/Departaments?$filter=startswith(Name,'%D0%9A%D0%98')

Update README.md with paging and Profiling Sql info (use with MiniProfiler)

If possible, update the README.md with the following info, so that newbies can understand the paged select support and the profiler support in linq2db. The reason I'm not doing a pull request is I'm not sure the verbiage I have put together would make sense for you.

For paged select queries, you can use the Skip and Take functions:

public static List<Product> GetByPage(int pageNumber, int pageSize)
{
  using (var db = new DbNorthwind())
  {
    //Always use a OrderBy clause for consistent paging
    var query = db.Product.OrderBy(p=>p.ProductID).Skip(pageNumber * pageSize).Take(pageSize);
    return query.ToList();
  }
}

Sql Logging

Logging SQLs generated by ORM is an essential part of debugging and troubleshooting performance issues, Linq2DB providers various methods to do that. The DataProviderBase class provides a hook to modify the IDbConnection, using this we can add support for additional profiling providers like MiniProfiler or custom profilers (log to a file or any other target with your favorite log library ) - https://gist.github.com/anonymous/9460950.

//In one of your static constructor 
DataProviderBase.OnConnectionCreated = delegate(IDataProvider dbProvider,IDbConnection dbConn)
{
  dbConn = new ProfiledDbConnection((DbConnection)dbConn, MiniProfiler.Current);

  //If you are using the Custom Profiler from the Gist, you can chain the profilers like this
  dbConn = new ProfiledDbConnection((DbConnection)dbConn, CustomDBProfiler.Instance);

  return dbConn; 
};

Linq2db (linq to sqlite) on .NET 4.0 ?

My company requires our product to target .Net 4.0, the compiler complains lin2db needs System.Data.Services 4.0.0.0, which seems to require .Net 4.5. Is there any chance of getting this working? or maybe this is some problem with my setup? To help answer this questions, please I would like to know if it's possible at all to work with linq2db on .NET 4.0 or if it was made depending heavily on 4.5.

Best regards.
Marcelo.

Linq2Access Yes/No (bit) fields not updating

I've just started using your library to do Linq queries with Access data. Great library!

Using the method db.Update(Table) to update records, Yes/No (bit) fields are not updated. And the same is true of db.InsertWidthIdentity(Table).

Problem wrong Object Mapper is used in query...

I've the following code:

 public static IQueryable<GlobalTaskExtendedDTO> GetGlobalTasksExtended(BLToolKitSessionWrapper<MFCV2DL> s)
    {
        var qry = s.Query<GlobalTaskDTO>();
        var qry2 = from g in qry
            join rp1 in s.GetTable<ResourcePointDTO>() on g.RPSourceId equals rp1.Id
            join rp2 in s.GetTable<ResourcePointDTO>() on g.RPDestinationId equals rp2.Id
            join res in s.GetTable<ResourceDTO>() on g.ResourceId equals res.Id
            select new GlobalTaskExtendedDTO(g) {RPSource = rp1.Name, RPDestination = rp2.Name, Labels = res.Labels};

        return qry2;
    }

where GlobalTaskDTO, ResourcePointDTO, ResourceDTO are Objects BLToolkit knows.

But GlobalTaskExtendedDTO is unkown to BLToolkit!

now the Problem ist, at query.cs in line 1108, bltoolkit trys to map the value res.Labels via the mapper of GlobalTaskExtendedDTO (wich it does not have)! It should use the mapper of ResourceDTO.

Any Idea whats going wrong here?

ISqlProvider missing from linqToDB.SqlProvider in version 1.0

Just installed the new version in my project and when running the .tt file for DB2 i get the following error.

Error 8 Compiling transformation: The type or namespace name 'ISqlProvider' does not exist in the namespace 'LinqToDB.SqlProvider' (are you missing an assembly reference?)

I check the source in Github and I do not see it there in the SqlProvider folder.

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.