Home > database >  Is there a way to use the DBContext class to access a entity whose table was created in OnModelCreat
Is there a way to use the DBContext class to access a entity whose table was created in OnModelCreat

Time:02-04

I have two classes: Article and Category. The Article owns the Category. In the DBContext(via EntityConfig file) I have the following being configured:

    jsConfiguration.OwnsMany(article => article.Categories, s =>
    {
        s.WithOwner();
        s.Property<DateTime>("CreatedDate");
        s.Property<DateTime>("UpdatedDate");
        s.ToTable("ArticleBaseCategories");
    });

Please accept that I have to configure it this way and not able to use DBSet.

I want to be able to use syntax similar to if I had a DBSet Categories property defined in my DBSeedClass. For example:

_context.Categories.Where(category => category.Name == "example")

Is there a way to do this without actually creating a DBSet<> property?

CodePudding user response:

No. Many different entities in your model can have the same owned entity type mapped to different tables, so EF wouldn't know where to fetch them. You can use Dapper and a raw SQL query to fetch them. Or fetch some Article entities, and then run .SelectMany(a => a.Categories) on the client.

  •  Tags:  
  • Related