【发布时间】:2020-01-21 21:03:58
【问题描述】:
我有一个这样的表架构:
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; }
}
还有OnModelCreating(ModelBuilder modelBuilder)方法:
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);
}
我有以下循环导航属性,这些属性将被创建,直到我点击Products:
如何避免循环导航属性?请告诉我我做错了什么?这是预期的正确行为吗?
【问题讨论】:
-
你不能,但你不需要——这没有错。 EF 也会把它们牢记在心
-
@CaiusJard 你的意思是这是正确的和预期的行为吗?
-
其实这和Entity Framework没有关系。这发生在任何引用其所有者的 C# 元素集合中,并且它应该发生。调试器不会创建新属性。它只是一次又一次地显示相同的产品和类别。
-
@GertArnold 随意回答,我会将其标记为答案!非常感谢!祝你有美好的一天!:)
标签: c# tsql asp.net-core entity-framework-core