When placing a class in DbSet using Migrations

1

I have the following classes:

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

being that 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 purposes, it turns out that I created another class Category and set up a relation many-to-many with the class (database table) Request , to my surprise, the new class was included in the migration, without my having identified it as DbSet . My question is this: if I create a new class X and it somehow relates to a class Y in DbSet then class X is added to the database automatically? In my case, you could remove this line:

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

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

    
asked by anonymous 08.06.2018 / 13:55

2 answers

1

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

As for needing to create a DbSet , it depends on how you use your context.

If you do not have a DbSet of the Category , you will not be able to do the following seuContexto.Categories.Find(id); , however, there is another way to "use" these methods, seuContexto.Set<SuaClasse>().Find(id); inside the diamond operator ( <> ) is informed which type.

  

In my case, you could remove this line:

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

09.06.2018 / 01:38
0

DbSet represents the "repository" of your entity that has the Create, Find, Remove, and so on methods. So, if you do not map the entity in dbset, you will not be able to do the Crud.

If you want, you can take a look at the link link

    
08.06.2018 / 16:47