zzzprojects / Dapper-Plus

Dapper Plus - High-Efficient Bulk Actions (Insert, Update, Delete, and Merge) for .NET
https://dapper-plus.net/
380 stars 84 forks source link

Adding a list property to another table #120

Closed xQxCPMxQx closed 1 year ago

xQxCPMxQx commented 1 year ago

I have a model as below:

public class Product
    {
        public int ProductId {get;set;}
        public string ProductName {get;set;}
        public IList<Guid> aList { get; set; }
    }

And the result in the model is like this: ProductId: 99901 ProductName: Product01 aList

How do I add this model to database like below?

Table Products: ProductId | ProductName 99901 | Product01

Table ProductListData: ProductId | ListValue from aList 99901 | wq222-33e2-2022-2a2s2-2ss4 99901 | as222-3e44-2002-2a2s2-2ss4 99901 | as2xg-3e44-2002-2a2s2-2ss4

I solve the problem with different methods, but I cannot change the structure of this model. I have to conform to this structure of the model.

I hope I was able to explain my problem. Thank you

JonathanMagnan commented 1 year ago

Hello @xQxCPMxQx ,

Is it possible for you to create another class or use an expando object?

For example, having something like this:

public static class MyExtensions
{
    public static List<ExpandoObject> ExpandProducts<T>(this List<Product> products)
    {
        var list = new List<ExpandoObject>();

        foreach(var product in products)
        {
            foreach(var a in product.aList)
            {
                // WOULD be better if you could create another class but otherwise, expando could work fine
                var expando = new ExpandoObject();
                expando.ProductId = product.ProductId;
                expando.ListValue = a;

                list.Add(expando);
            }
        }

        return list;
    }
}

// Map
DapperPlusManager.Entity<ExpandoObject>("productListData").Table("ProductListData");

// Insert
connection.BulkInsert(products);
connection.BulkInsert("productListData", products.ExpandProducts());

(code has not been tested so might contains some coding mistake)

Let me know if that solution could work for you.

Best Regards,

Jon

xQxCPMxQx commented 1 year ago

I don't know how much to thank you. It works great!!! Thank you so much!