LINQ 2 DB insert dynamic into table

1.3k Views Asked by At

I want to use dynamic in order to be able to choose which columns to define and those I want to let the DB set the DEFAULT value. Is there a way to insert a dynamic into a table and return the Id?

I tried various overloads both on DataConnection and ITable<> but the only result I could achieve is getting the count of affected rows.

This is my code:

Person table schema

CREATE TABLE [dbo].[Person] (
    [Id]        BIGINT       IDENTITY (1, 1) NOT NULL,
    [Name]      VARCHAR (50) NOT NULL,
    [Surname]   VARCHAR (50) NOT NULL,
    [BirthDate] DATE         DEFAULT (getdate()) NOT NULL
);

.NET Core Console App

public class Person
{
    public uint Id { get; set; }
    public string Name { get; set; }
    public string Surname { get; set; }
    public DateTime BirthDate { get; set; }
}
public class PeopleDataConnection : DataConnection
{
    public PeopleDataConnection(string connectionString)
        : base(ProviderName.SqlServer, connectionString)
    { }

    public ITable<Person> People => this.GetTable<Person>();
}
class Program
{
    static async Task Main(string[] args)
    {
        await using (var db = new PeopleDataConnection("Server=DESKTOP-I41VSUN;integrated Security=SSPI;Database=MotoGPRiders;"))
        {
            var dynamicPerson = new { Name = "Cal", Surname = "Crutchlow", BirthDate = new DateTime(1985, 10, 29) };
            var person_without_id = new Person { Name = "Valentino", Surname = "Rossi", BirthDate = new DateTime(1979, 2, 16) };

            var affectedRowsCount = await db.InsertAsync(dynamicPerson, nameof(Person));
            affectedRowsCount = await db.People
                .Value(x => x.Name, person_without_id.Name)
                .Value(x => x.Surname, person_without_id.Surname)
                .Value(x => x.BirthDate, person_without_id.BirthDate)
                .InsertAsync();
        }
        Console.ReadLine();
    }
}

The first insert does the job but can't return the Id, the second lets me choose the columns but not dynamically.

Is there a way to achieve this? Thanks in advance!

1

There are 1 best solutions below

0
On

You can retrieve identity value via InsertWithInt64IdentityAsync function. There a lot of overloads for such insert:

var insertedId = await db.People
            .Value(x => x.Name, person_without_id.Name)
            .Value(x => x.Surname, person_without_id.Surname)
            .Value(x => x.BirthDate, person_without_id.BirthDate)
            .InsertWithInt64IdentityAsync();

Also you can filter out properties which has to be inserted via overload which has columnFilter parameter:

var insertedId = await db.InsertAsync(person, 
    e => e.MemberName.In("Name", "Surname", "BirthDate"));

For variant with anonymous class, you have to create your own function which generates calls via reflection using Value.Value.Value + InsertWithInt64IdentityAsync calls:

public static class DynamicExtensions
{
    public static IValueInsertable<T> GenerateInsertable<T>(this ITable<T> table, object obj)
    {
        var dynamicAccessor = TypeAccessor.GetAccessor(obj.GetType());
        var accessor = TypeAccessor.GetAccessor<T>();
        var objValue = Expression.Constant(obj);
        IValueInsertable<T> insertable = null;
        foreach (var dynamicMember in dynamicAccessor.Members)
        {
            var found = accessor.Members.Find(m => m.Name == dynamicMember.Name);
            if (found == null)
                continue;
            var sourceParam = Expression.Parameter(typeof(T), "e");
            var property = Expression.Lambda(Expression.MakeMemberAccess(sourceParam, found.MemberInfo),
                sourceParam);
            Expression value = Expression.MakeMemberAccess(objValue, dynamicMember.MemberInfo);
            if (value.Type != found.Type)
                value = Expression.Convert(value, found.Type);
            value = Expression.Lambda(value);

            if (insertable == null)
            {
                var method = Methods.LinqToDB.Insert.T.ValueExpression.MakeGenericMethod(typeof(T), found.Type);
                insertable = (IValueInsertable<T>)method.Invoke(null, new object[] { table, property, value });
            }
            else
            {
                var method = Methods.LinqToDB.Insert.VI.ValueExpression.MakeGenericMethod(typeof(T), found.Type);
                insertable = (IValueInsertable<T>)method.Invoke(null, new object[] { insertable, property, value });
            }
        }

        return insertable;
    }

    public static long? InsertWithIdentityDynamic<T>(this ITable<T> table, object obj)
    {
        var insertable = GenerateInsertable(table, obj);
        if (insertable == null)
            return null;
        
        return insertable.InsertWithInt64Identity();
    }

    public static async Task<long?> InsertWithIdentityDynamicAsync<T>(this ITable<T> table, object obj, CancellationToken cancellationToken = default)
    {
        var insertable = GenerateInsertable(table, obj);
        if (insertable == null)
            return null;

        return await insertable.InsertWithInt64IdentityAsync(cancellationToken);
    }
}

And usage:

var insertedId = await db.GetTable<Person>()
    .InsertWithIdentityDynamicAsync(dynamicPerson);