Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adding a list property to another table #120

Closed
xQxCPMxQx opened this issue Nov 8, 2022 · 2 comments
Closed

Adding a list property to another table #120

xQxCPMxQx opened this issue Nov 8, 2022 · 2 comments
Assignees

Comments

@xQxCPMxQx
Copy link

xQxCPMxQx commented Nov 8, 2022

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

  • as222-3e44-2002-2a2s2-2ss4
  • as2xg-3e44-2002-2a2s2-2ss4
  • wq222-33e2-2022-2a2s2-2ss4

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 JonathanMagnan self-assigned this Nov 9, 2022
@JonathanMagnan
Copy link
Member

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
Copy link
Author

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

No branches or pull requests

2 participants