我有一个这样的表架构:
CREATE TABLE Categories
(
Id INT IDENTITY(1,1),
Name varchar(100),
CONSTRAINT PK_Category_Id PRIMARY KEY (Id)
)
CREATE TABLE Products
(
Id INT IDENTITY(1,1),
IdCategory INT NOT NULL
CONSTRAINT FK_Products_IdCategory__Categories_Id FOREIGN KEY(IdCategory) REFERENCES Categories(Id),
Name varchar(100),
Price decimal(18,2),
ImageUrl varchar(256),
CONSTRAINT PK_Product_Id PRIMARY KEY (Id)
)
EF Core 生成了以下代码:
public partial class Categories
{
public Categories()
{
Products = new HashSet<Products>();
}
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Products> Products { get; set; }
}
public partial class Products
{
public Products()
{
OrderItems = new HashSet<OrderItems>();
ShoppingCartItems = new HashSet<ShoppingCartItems>();
}
public int Id { get; set; }
public int IdCategory { get; set; }
public string Name { get; set; }
public decimal? Price { get; set; }
public string ImageUrl { get; set; }
public virtual Categories IdCategoryNavigation { get; set; }
public virtual ICollection<Items> Items { get; set; }
}
And OnModelCreating(ModelBuilder modelBuilder)
method:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.HasAnnotation("ProductVersion", "2.2.6-servicing-10079");
modelBuilder.Entity<Categories>(entity =>
{
entity.Property(e => e.Name)
.HasMaxLength(100)
.IsUnicode(false);
});
modelBuilder.Entity<Products>(entity =>
{
entity.Property(e => e.ImageUrl)
.HasMaxLength(256)
.IsUnicode(false);
entity.Property(e => e.Name)
.HasMaxLength(100)
.IsUnicode(false);
entity.Property(e => e.Price).HasColumnType("decimal(18, 2)");
entity.HasOne(d => d.IdCategoryNavigation)
.WithMany(p => p.Products)
.HasForeignKey(d => d.IdCategory)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("FK_Products_IdCategory__Categories_Id");
});
}
我编写了以下代码:
public override async Task<Products> GetById(int id)
{
return await DbContext.Products
.Include(p => p.IdCategoryNavigation)
.FirstOrDefaultAsync(p => p.Id == id);
}
And I've got the following circular navigation properties and these properties will be created until I click on Products
:
如何避免循环导航属性?请告诉我我做错了什么?这是预期的且正确的行为吗?