如何使用 AutoPersistenceModel 创建与同一对象的父/子关系
我的项目中有以下类,
public class ProductCategory
{
public virtual Guid Id { get; set; }
public virtual string UrlSlug { get; set; }
public virtual string Title { get; set; }
public virtual bool IsActive { get; set; }
public virtual IList<Product> Products { get; set; }
public virtual ProductCategory Parent { get; set; }
public virtual IList<ProductCategory> Categories { get; set; }
}
我的数据库表如下:
CREATE TABLE [dbo].[ProductCategory](
[Id] [uniqueidentifier] NOT NULL,
[UrlSlug] [nvarchar](255) NULL,
[Title] [nvarchar](255) NULL,
[IsActive] [bit] NULL,
[ProductCategory_id] [uniqueidentifier] NULL -- this is the parent category id
)
我试图允许一个类别成为另一个类别的子级,显然,父级可以有多个类别。
我在让 AutoPersistenceModel 工作时遇到问题。这就是我的映射。
.ForTypesThatDeriveFrom(map =>
{
map.HasMany(productCategory => productCategory.ProductCategories).WithForeignKeyConstraintName("ProductCategory_id");
map.HasOne(productCategory => productCategory.ParentCategory).WithForeignKey("ProductCategory_id");
});
我尝试了一些不同的方法,但对我来说没有用。它似乎正确映射了 HasMany。但当数据库中的 ParentCategory_id 为 null 时,HasOne 最终会成为其本身,而不是正确的父实体,或者什么都没有(null)
I have the following class in my project
public class ProductCategory
{
public virtual Guid Id { get; set; }
public virtual string UrlSlug { get; set; }
public virtual string Title { get; set; }
public virtual bool IsActive { get; set; }
public virtual IList<Product> Products { get; set; }
public virtual ProductCategory Parent { get; set; }
public virtual IList<ProductCategory> Categories { get; set; }
}
my database table is as follows:
CREATE TABLE [dbo].[ProductCategory](
[Id] [uniqueidentifier] NOT NULL,
[UrlSlug] [nvarchar](255) NULL,
[Title] [nvarchar](255) NULL,
[IsActive] [bit] NULL,
[ProductCategory_id] [uniqueidentifier] NULL -- this is the parent category id
)
I am trying to allow for a Category to be a child of another, and obviously, the parent could have multiple categories.
I am having troubles getting my AutoPersistenceModel to work. This is what I have for my mapping.
.ForTypesThatDeriveFrom(map =>
{
map.HasMany(productCategory => productCategory.ProductCategories).WithForeignKeyConstraintName("ProductCategory_id");
map.HasOne(productCategory => productCategory.ParentCategory).WithForeignKey("ProductCategory_id");
});
I've tried a few different things that just haven't worked for me. It seems to map the HasMany correctly. But the HasOne ends up being itself, rather than the correct parent entity, or nothing (null), when the ParentCategory_id is null in the database
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
安东尼,尝试将其更改为这个。
has one 是一对一的关系,您希望将另一个类引用为父类。
Anthony, try changing the has one to this.
The has one is a one-to-one relationship you're looking to reference another class as a parent.
我们在一个项目中做了类似的事情,这是我们使用的约定:
We do something similar in one of our projects, this is the convention we use: