Home > database >  Option to join objects in list with list from other db
Option to join objects in list with list from other db

Time:10-14

I have 2 databases and folowing models

For db 1:

Public class StorageItem
{
    public int Id { get; set; }
    public string Name { get; set; }    
}

for db 2:

public class Storage
{
    public int Id { get; set; }
    publict string name {get; set;}
    public int StorageItemId{ get; set; } 
}

I have the methods

var storageitemList = context.StorageItem.ToList();

and

var storageList = context.Storage.ToList();

I would like to add to the corresponding name from the storageitemList to the StorageList. StorageList will result in something like this and each storagelist object is still accessible.

ID NAME
1 test
2 test2
id name storageitemId StorageItemName
1 test12 1 test
2 test4 2 test2

Currently the string name is stored in the database but this will be changed to the Id. But the name needs still be showed in the Razor/blazor frontend page like now. Do i need to make a new Class to combine them or a property bag? What is the best solution to achieve this?

I started looking at PropertyBag to achieve something like: Status["name"]=storageitemlist.where(si=> si.id == storage.id); but cant find the propertybag solution for models. thanks in advance

CodePudding user response:

You should clarify what you need exactly ... What I did understand from the post is you need something like Zip operation in linq

from (C# in nutshell)

The Zip Operator

IEnumerable<TFirst>, IEnumerable<TSecond>→IEnumerable<TResult>

The Zip operator was added in Framework 4.0. It enumerates two sequences in step (like a zipper), returning a sequence based on applying a function over each element pair.

For instance, the following:
int[] numbers = { 3, 5, 7 };
string[] words = { "three", "five", "seven", "ignored" };
IEnumerable<string> zip = numbers.Zip (words, (n, w) => n   "="   w);

produces a sequence with the following elements:

3=three
5=five
7=seven

Extra elements in either input sequence are ignored. Zip is not supported by EF Core.

CodePudding user response:

      var query = (from storage in storageList
                         join storageitem in storageitemList on storage.StorageItemId equals storageitem.Id
                         select (storage: storage, storageitem: storageitem)).ToList();

And List<(Storage storage, StorageItem storageitem)> has model in your view

You can also create a new dto class for the model

it is better to avoid using the viewbags

  • Related