J
J
JoraInTheSky2017-07-13 01:53:21
SQL
JoraInTheSky, 2017-07-13 01:53:21

Linq, many-to-many relationship in EF?

There is a database implemented many-to-many relationship through the intermediate table ProductRepo.
742940c398b048a684fce35b9eb771bc.JPG
After screwing the database into the project through EF, the database comes out without an intermediate table with a many-to-many relationship. 12658c0b452e417793d552e0759461d4.JPG
With such a query to the database:

Select Product.Name, Product.Price, Product.Count, Repository.Name
from Product, Repository, ProductRepo 
where Product.Id = ProductRepo.IdProduct AND Repository.Id = ProductRepo.IdRepository
I get the result
6e7daf3434504462b7161176926086dc.JPG
that I need.
But, when I try to get the same result through LINQ, I get trouble.
There was already a similar question and it was advised to do this:
var query = db.Products.Include(x => x.Repositories).ToList();

But it gives the following error:
4c981169f3d046ae9ba080ddaee9e283.png
With this request:
var query = db.Products.Include("Repositories").ToList();

and passing the result to the view is already closer to the truth, but:
fcf36ba470f9475bba9b6f27f2e46a0d.JPG
But in debugging it shows that there is a property I need:
c1c995891e6a4dc38784ba1e06882ccc.png
Now the question is: how to write a LINQ query correctly to get a similar one
Select Product.Name, Product.Price, Product.Count, Repository.Name
from Product, Repository, ProductRepo 
where Product.Id = ProductRepo.IdProduct AND Repository.Id = ProductRepo.IdRepository

or how to pull the property I need:
951cbecef1e2482dbdc3516d0232826c.png

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander Kuznetsov, 2017-07-13
@JoraInTheSky

In general, there are several options. We can manually add the desired linking table to the context.
Or do something like this:

var data = db.Products.Include("Repositories");
var values = new List<ProductWithRepoDTO>();

foreach(var record in data)
{
    var reposArray = record.Repositories.Select(x=>x.Name).ToArray();
    var reposString = string.Join(",", reposArray);
    
    values.Add(new ProductWithRepoDTO
    {
        Id = record.Id,
        Name = record.Name,
        Cound = record.Count,
        Price = record.Price,
        Repository = reposString 
    });        
}
//дальше работать с values

The second approach, in my opinion, is more correct, because. you are no longer working with a domain model, but with a view model that already contains data that is convenient for displaying .

A
aynur_safin, 2017-07-13
@aynur_safin

But it gives this error:
Connect
using System.Data.Entity;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question