admin管理员组

文章数量:1401592

I'm trying to follow the npgsql guide to map a class to a JSON column, but I cannot get past the following error:

System.InvalidOperationException: The entity type 'MainCategory' is not mapped to a table, therefore the entities cannot be persisted to the database. Call 'ToTable' in 'OnModelCreating' to map it to a table.

I have a model like this:

public class Post
{
    // ...
    public MainCategory MainCategory { get; set; }  
}

public class Category
{
}

public class Category<TParent> where TParent: Category
{
    // ...
    [JsonIgnore] 
    public TParent Parent { get; set; }
}

public class Category<TParent, TChildren> where TParent: Category, where TChildren: Category
{
    [Column(TypeName = "jsonb")] 
    public ICollection<Category> Children { get; set; }
}

public class MainCategory : Category<Category, Category>
{
}

With the following context:

public class MyContext : DbContext 
{
    public DbSet<Post> Posts => Set<Post>();

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Post>()
            .OwnsOne(c => c.MainCategory, r =>
            {
                r.ToJson();
                r.OwnsMany(c => c.Children);
            });

         base.OnModelCreating(modelBuilder);
    }
} 

The child categories have different properties so it's important for me to have the correct parent/child relationship across them - which would be very difficult if it was just Category all the way.

I also tried using two interfaces to represent parent/children, but I always end up with the same error. If I remove [Column(TypeName = "jsonb")] from Children, then I get

System.InvalidOperationException: 'Unable to determine the relationship represented by navigation 'OneOfTheSubCategories.Children' of type 'ICollection<Category>'. Either manually configure the relationship, or ignore this property using the '[NotMapped]' attribute or by using 'EntityTypeBuilder.Ignore' in 'OnModelCreating'.'

I'm not sure what I'm doing wrong or if this is an unsupported scenario altogether. I can use just string and do manual conversion on the Post class if needed, but I'm trying to avoid that.

This is using latest .NET 9.0 versions.

本文标签: cThe entity type is not mapped to a tableignores ToJson callStack Overflow