Reputation: 1
I have the entities Products and Tags. I have many to many relationship between the 2 tables, so I have tertiary table.
My Product Entity:
public class Product
{
public Guid Id { get; private set; }
public string Name { get; private set; }
public List<ProductTags> ProductTags { get; private set; }
}
My Tag Entity:
public class Tag
{
public Guid Id { get; private set; }
public string Description { get; private set; }
public List<ProductTags> ProductTags { get; private set; }
}
My ProductTags Entity:
public ProductTags
{
public Guid ProductId { get; private set; }
public Product Product { get; private set; }
public Guid TagId { get; private set; }
public Tag Tag { get; private set; }
}
How can I get my Tags related to my Product using Entity Framework Core?
Sorry for errors, my knowledge in English is very low.
Upvotes: 0
Views: 531
Reputation: 1823
As far as I know the latest version of EF Core 2.1.4
doesn't support Many-to-Many feature as EF 6.2
did out the box. Therefore, you should have 3rd table explicitly (ProductTags in your case).
You could find sample of mapping configuration here
How you can get Tags related to Product? There are dozens ways to do it, but the most appropriate (using EF and extension methods) will be:
var tagsByProduct = await context.ProductTags
.Where(item => item.ProductId == 100500)
.Select(item => item.Tag)
.ToListAsync();
or
var tagsByProduct = await context.ProductTags
.Where(item => item.Product.Name == "ProductName")
.Select(item => item.Tag)
.ToListAsync();
or
var tagsByProduct = await context.ProductTags
.Where(item => item.Product.Name == "ProductName")
.Select(item => new { Id = item.Tag.Id, Description = item.Tag.Description })
.ToListAsync();
depend on you requirements.
Moreover, you could write joins explicitly, it will work a little bit faster.
Upvotes: 1