I am very new to development with ORMs.
In my project, where I use Entity Framework Core, I want to create a class that would encapsulate whole interaction with database, i.e. through which I would add new entities to database, remove them and retrieve them.
From what I understand, interaction happens by accessing DbSet properties of the DbContext class and looks something like this:
public void Add( DummyObject objectToAdd)
{
using (MyContext context = new MyContext())
{
/* check if entity with such primary key already exists in database */
/* Here, DummyObjects is a name of DbSet property from DbContext */
Context.DummyObjects.Add(objectToAdd);
}
}
What I am stuck with is when I try to write logic for a type that isn't known at compile time, I can't access DbSet properties by name. I know, there is a Set method in the DbContext class, but it uses generics, and therefore I can't use it neither as generics have to be specified at compile time and won't accept something like this <interfaceVariable.GetType()>.
At this point, I believe there are these options left:
To use reflection, which would bring unnecessary penalty on performance and, I believe, is not intended for such cases.
To write a class using generics, and use a dictionary with mappings type to
DbInteractionClass<EntityType>, which means to have potentially huge list.
There was a question on this resource about how to access DbSet when it is known only at runtime which DbSet will be used, and the answer was to use the version of Set() method which didn't use generics and which isn't available in modern versions of EF Core.
I want to create a class that would encapsulate whole interaction with databasethat's what EF already does. Your application doesn't even know if it's talking to MySQL, SQLite or a NoSQL database like MongoDB. You aren't talking to the database at all here, you're loading entire graphs of related objects at once, and persisting changes to all of them..Set<T>()anyway..Set<>()also caches, so the perf hit is less.Adddoesn't add. It attaches a new object and all its child objects in theAddedstate. WhenSaveChangesis finally called to persist all changes, objects in theAddedstate are always inserted. It would be better to useUpdateinstead - in this case the value of the PK attributes is used to determine whether to attach the object in theAddedorModifiedstate.