mtanneryd / ef-bulk-operations

Bulk operations for Entity Framework 6

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Regex to get table name gives empty string.

tallalkazmi opened this issue · comments

The following Regex that you are using gives empty string:
var regex = new Regex(@"FROM (?<table>[\[\w@$#_\. \]]+) AS \[\w+\]$") and this error is not handled.

The SQL statement generated from my code is:
SELECT [Extent1].[Id] AS [Id], [Extent1].[Identifier] AS [Identifier], [Extent1].[Name] AS [Name], [Extent1].[Latitude] AS [Latitude], [Extent1].[Longitude] AS [Longitude], [Extent1].[FIR] AS [FIR], [Extent1].[UIR] AS [UIR], [Extent1].[ICAO] AS [ICAO], [Extent1].[MagneticVariation] AS [MagneticVariation], [Extent1].[Frequency] AS [Frequency], [Extent1].[CountryName] AS [CountryName], [Extent1].[CountryId] AS [CountryId], [Extent1].[StateId] AS [StateId], [Extent1].[CityId] AS [CityId], [Extent1].[IsActive] AS [IsActive] FROM [dbo].[Points] AS [Extent1] WHERE ([Extent1].[IsActive] = @DynamicFilterParam_000001) OR (@DynamicFilterParam_000002 IS NOT NULL)

Ill generate a pull request fixing this issue and added additional exception handling, please be kind enough to merge this and release on nuget. Thanks.

File: DbContextExtensions.cs
LIne: 2201

Capture

I am not able to commit changes. Here are the changes which i did to make it work:

`
public static TableName GetTableName(this DbContext ctx, Type t)
{
var dbSet = ctx.Set(t);
var sql = dbSet.ToString();

        //Gives empty tablename
        //var regex = new Regex(@"FROM (?<table>[\[\w@$#_\. \]]+) AS \[\w+\]$");

        //Simplified Regex to get everything between FROM and first occurrence of AS then trim the string value.
        var regex = new Regex(@"FROM(?<table>.*?)AS");
        var match = regex.Match(sql);
        var name = match.Groups["table"].Value.Trim();

        //Added empty tablename exception handling.
        if(string.IsNullOrWhiteSpace(name))
            throw new ArgumentException($"Failed to parse tablename. Bulk operation failed.");

        var n = name.Replace("[", "").Replace("]", "");
        var m = Regex.Match(n, @"(.*)\.(.*)");
        if (m.Success)
        {
            return new TableName { Schema = m.Groups[1].Value, Name = m.Groups[2].Value };
        }

        m = Regex.Match(n, @"(.*)");
        if (m.Success)
        {
            return new TableName { Schema = "dbo", Name = m.Groups[1].Value };
        }

        throw new ArgumentException($"Failed to parse tablename {name}. Bulk operation failed.");
    }

`

Tallal Kazmi, which version are you using?

Yes, the 1.3.1-beta1 fixes the issue. You can move to an official 1.3.1 so I can too move my code to production. Thanks for your prompt response and a great library.