C# 如果没有外键,为什么实体框架核心会生成导航属性?
我有这个表模式:C# 如果没有外键,为什么实体框架核心会生成导航属性?,c#,sql-server,tsql,asp.net-core,entity-framework-core,C#,Sql Server,Tsql,Asp.net Core,Entity Framework Core,我有这个表模式: 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_IdCateg
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)
)
实体框架核心生成以下域类:
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; }
}
公共部分类类别
{
公共类别()
{
Products=新的HashSet();
}
公共int Id{get;set;}
公共字符串名称{get;set;}
公共虚拟ICollection产品{get;set;}
}
公共部分类产品
{
公共产品()
{
OrderItems=newHashSet();
ShoppingCartItems=new HashSet();
}
公共int Id{get;set;}
public int IdCategory{get;set;}
公共字符串名称{get;set;}
公共十进制?价格{get;set;}
公共字符串ImageUrl{get;set;}
公共虚拟类别IdCategoryNavigation{get;set;}
公共虚拟ICollection项{get;set;}
}
我的问题是:
类别
类中生成公共虚拟ICollection产品{get;set;}
李>
产品
但产品中有一个指向类别的FK。当两个表之间有一个FK时,导航属性将在两个方向上运行。你为什么不想要呢?另外,看起来还有一个带有FK to Products的Items表,因此Products中的Items导航属性。你也想摆脱它吗?@juharr我想删除一个导航属性
Categories.Products
,正因为如此。因此,在您的评论之后,我认为我所有的代码都是正确的,并且实现正确。请随便回答,我会把你的回答标记为回答。谢谢
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; }
}