問題描述
如何使用 LINQ 和 ASP.NET MVC 持久化用戶與其關聯的數據庫? (How do I persist which database a user is associated with it using LINQ and ASP.NET MVC?)
I have an app I must write that will utilize a database for each company we are able to get as a client.
Unfortunately, the schemas for all the companies databases's are not identical, even though for this app they all have the basic information I need (even if their column names are different/in a different table).
My solution to handling the multiple databases is to create an IRepository interface like:
List<User> getUsers();
List<Account> getAccounts();
void UpdateAccount(Account account);
etc.
I'll write a DAL class for each database which will implement this interface. This class will use the appropriate LINQ datacontext for it's own database:
Here you can see the folders for Lowes, HomeDepot, and FrankLumber. Each one has a DAL class which implements IRepository.
My question is, where should I handle the instantiation of the factory method so I can persist a new DAL class instance for each user who logs in, based on what "company" they belong to.
So, if a lowes customer logs in it will call the RepositoryFactory passing it the user and return the appropriate DAL, which I can then call methods on polymorphically since I know they will implement the above methods.
I'm new to ASP.NET MVC and MembershipProviders and could use some tips on how I should persist the instance of the DAL for each user after they log in.
參考解法
方法 1:
You can instantiate the DAL instances in your controller actions. If you have really have a lot of actions, then you can think of creating the DAL instance in some better place that is shared among actions (like attributes)
You can persist in the the ASP.NET Session state, or create the database context again every time you need it (just make sure you close the datacontext each time again, best use the 'using' keyword on the datacontext)
(by KingNestor、chris166)