Sto utilizzando Entity Framework Core e Fluent API.
Sto cercando di implementare un array relativo ai prodotti incluso nel mio modello di prodotto in questo modo:
{
"id": 13
"name": "something",
"heading": "something else",
"summary": "please put me out my misery!"
"relatedProducts": [
{
"name": "something related",
"heading": "something else related",
"summary": "something in summary"
},
{
"name": "something related",
"heading": "something else related",
"summary": "something in summary"
}
]
}
Al momento ho questo nel mio contesto:
modelBuilder.Entity<RelatedProduct>()
.HasKey(r => new { r.ProductId, r.RelatedId });
modelBuilder.Entity<RelatedProduct>()
.HasOne(p => p.Product)
.WithMany(r => r.RelatedProducts)
.HasForeignKey(p => p.ProductId)
.OnDelete(DeleteBehavior.Restrict);
modelBuilder.Entity<RelatedProduct>()
.HasOne(p => p.Related)
.WithMany(r => r.ProductsRelated)
.HasForeignKey(p => p.RelatedId)
.OnDelete(DeleteBehavior.Restrict);
La mia classe di prodotto correlato si presenta così:
public class RelatedProduct
{
public int ProductId { get; set; }
public virtual Product Product { get; set; }
public int RelatedId { get; set; }
public virtual Product Related { get; set; }
}
Il problema è che il mio array ProductProduct sta tornando vuoto anche se ho collegato gli ID nel db.
Qualsiasi aiuto su questo sarebbe fantastico visto che non voglio finire con il "Body"!
Devi Include
i prodotti correlati (a meno che il Caricamento Lazy non sia abilitato) mentre stai effettuando una query. Quindi puoi fare la tua richiesta come segue:
var product = _dbContext.Products.Include(p => p.RelatedProducts)
.ThenInclude(rp => rp.Related)
.FirstOrDefault(p => p.Id == productId);
Ora il prodotto desiderato avrà i suoi prodotti correlati.
Meglio proiettare la tua domanda come segue:
var product = _dbContext.Products.Select(p => new
{
p.Id,
p.Name,
p.Heading,
p.Summary
RelatedProducts = u.RelatedProducts.Select(rp => rp.Related).ToList()
}).FirstOrDefault(p => p.Id == productId);
Qui il product
è di tipo anonimo. Se vuoi puoi farlo fortemente tipizzato proiettando la query su un ViewModel
come segue:
public class ProductDetailsViewModel
{
public int Id {get; set;}
public string Name {get; set;}
public string Heading {get; set;}
public string Summary {get; set;}
public List<Product> RelatedProducts {get; set;}
}
Quindi nella query:
var product = _dbContext.Products.Select(p => new ProductDetailsViewModel
{
Id =p.Id,
Name = p.Name,
Heading = p.Heading,
Summary = p.Summary
RelatedProducts = p.RelatedProducts.Select(rp => rp.Related).ToList()
}).FirstOrDefault(p => p.Id == productId);