Ich verwende .NET Core 2.0. Ich habe geschrieben, eine Menge für Navigationseigenschaften Ich weiß, dass das automatische faule Laden auf EF Core zu diesem Zeitpunkt nicht unterstützt. Ich verwende Microsoft-Ansatz, um Navigationseigenschaften zu erstellen. Ich versuche, eine Viele-zu-Viele-Beziehung zu schaffen.So erstellen Sie eine benutzerdefinierte Navigationseigenschaft für EF Core
Zuerst erstellen manuell Zuordnungstabelle, die auch in ApplicationDbContext wie neu DbSet enthalten
public class ProductCategory
{
[Key]
public int ProductId { get; set; }
[ForeignKey("ProductId")]
public virtual Product Product { get; set; }
[Key]
public int CategoryId { get; set; }
[ForeignKey("CategoryId")]
public virtual Category Category { get; set; }
}
public class Product
{
public int Id { get; set; }
public virtual ICollection<ProductCategory> ProductCategory { get; set;
}
public class Category
{
public int Id { get; set; }
public virtual ICollection<ProductCategory> ProductCategory { get; set;
}
In OnModelCreating Klasse
builder.Entity<ProductCategory>()
.HasKey(x => new { x.CategoryId, x.ProductId });
builder.Entity<ProductCategory>()
.HasOne(x => x.Product)
.WithMany(x => x.ProductCategory)
.HasForeignKey(x => x.ProductId);
builder.Entity<ProductCategory>()
.HasOne(x => x.Category)
.WithMany(x => x.ProductCategory)
.HasForeignKey(x => x.CategoryId);
Wenn ein neues Objekt in Abbildungstabelle hinzugefügt wird.
var productCategory = new ProductCategory
{
CategoryId = 1,
ProductId = 1
};
db.ProductCategory.Add(productCategory);
db.SaveChanges();
Artikel erfolgreich hinzugefügt, danach versuchen, Produkt oder Kategorie zuzugreifen Navigationseigenschaft zu testen, aber nur die aktuelle Klasse in dem Mapping erhält table.You das Beispiel sehen kann, wenn I`m Produkt aus der Kategorie zuzugreifen versuchen, Klasse:
model.Categories = this._categoryService
.All()
.Include(x => x.ProductCategory)
.ToList();
Produktklasse ist null?
Ich kann nicht hinzufügen. ThenInclude (x => x.Product), weil ProductCategory Enumeration und x auf Lambda Enumeration ist. Ich habe es auch mit .ThenInclude versucht (x => x.Select (x => x.Product)), funktioniert aber immer noch nicht! –
@DTodorov Was Sie versucht haben, ist für EF6. Das obige funktioniert, es gibt nur ein bekanntes Problem mit VS Intellisense. 'ThenInclude' hat zwei Überladungen - eine für die Spulenauswahl und eine für die Referenz. Siehe https://stackoverflow.com/questions/45658411/ef-core-second-level-theninclude-missworks/45658984#45658984 –
Was zum ... ja jetzt funktioniert gut! Danke vielmals ! –