When placing a class in Dbset using Migrations

Asked

Viewed 65 times

1

I have the following classes:

public DbSet<Request> Requests { get; set; }
public DbSet<Answer> Answers { get; set; }

where they have a one-to-Many relationship.

When I want a class to be added to my Entityframework migration model, I have to add it as I have in the above code, for mapping reasons, it turns out I created another class Category and set up a Many-to-Many relationship with the class (table in the database) Request, to my surprise, the new class was included in the migration, without me having identified it as DbSet. My question is this: whether I create a new class X and it somehow relates to a class Y in the DbSet then class X is added to the database automatically? In my case, could you remove this line:

 public DbSet<Answer> Answers { get; set; }

without changing the behavior? (this class is related to the class Request).

2 answers

1


The class creation behavior in the database is already expected because of the relationship, having a relationship with the class Category it will understand that there is a field "FK" and for this to occur need the table in the database.

As to need to create a DbSet, depends on how you use your context.

In case you don’t have one DbSet class Category, you won’t be able to do the following seuContexto.Categories.Find(id);, however, there is another way to "use" these methods, seuContexto.Set<SuaClasse>().Find(id); note that within the diamond operator(<>) is informed what type.

In my case, I could remove this line:

(opinion)I do not advise you to do it this way, you may get confused and may get lost, or use everything with DbSet, or "uses" everything with the seuContexto.Set<SuaClasse>(), maintain the standard.

  • Thank you! That’s right

0

  • but the structure in SQL is created in the same, then I noticed that I could not access the entity within the code to make changes, read, etc.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.