I'd like to insert my UserCompany
object into the database trought a single method. Such as passing the element to this function, take it and "insert in the right table".
Usually in Entity (such as LINQ to XML) I do somethings like:
db.Company.UsersCompany.Add(UserCompany);
db.SubmitChanges();
but the problem here is that I need to specify the table UsersCompany
and Company
before using the .Add()
.
I'd like (since I want to do ONE function for the insert for each type of object/table) get rid of this. Such as having a:
UserCompany.InsertMySelf();
or
db.SmartAdd(UserCompany);
and it know how to insert the table, where and how, automatically.
Is it possible to do this? Is there any strategies?
You can solve this with generics:
Sorry for using VB... In C#:
You need to look at the generic repository. This pattern feeds all the CRUD through one base class. You can then inherit from this class to implement custom repositories where it's necessary
References:
The repository and unit of work patterns
John Papa's original source
How to ensure proxies are created when using the repository pattern
Generic Repository Pattern
In your
Controller
define a repository for yourself along these lines:Define a repository with the definition:
There will have to be some adaption to suite your own needs, but this is the general idea.
Although there could potentially be a lot of cases within the switch, I assume you will do object validation and other things regardless, so you can easily do that here too.
Relevant links: