Create and use multiple database for single application - c#

I am creating a system which will have multiple customer. right now i am using same database and table for all customer but i think it'll slow down fetching of record when i'll have hundreds of customer's data in same database.
so should i create separate database for each new registered customer dynamically by executing scripts from code? (will use master database to manage all user's connectionstrings)
I'm using entity framework. so same will be possible using EF? will it cause any problem?

May be you can use ABP framework to handle multiple database with entity framework.
ABP will help you to auto register repositories into IocContainer by adding attribute of all your DBContext (Each DBContext connect to a DB) as following:
[AutoRepositoryTypes(
typeof(IRepository<>),
typeof(IRepository<,>),
typeof(SimpleTaskSystemEfRepositoryBase<>),
typeof(SimpleTaskSystemEfRepositoryBase<,>)
)]
public class SimpleTaskSystemDbContext : AbpDbContext
{
...
}

Related

how deal with Dbcontext and Dbset?

I work with one application connected with 3 databases same structure just the data inside different.
I used WinForms with entity framework 6 .Net not Core when user login he choose the database.
how I made function to send dbcontext or dbset from chosen database?
for example I have a Site table have same columns and same names after user login need to fill datagridview with data from database that user choose.
I did it but with duplicate the code for every database :(
If the databases are truly identical, then you should only need to use one of three different connectionstrings when initializing the dbcontext. Maybe have the first one as the default one for entity framework for building models etc.
Here is an example of how to set the connectionstring in code:
Entity Framework 6 set connection string in code
Good luck!!

Will migrations affect my database?

I am learning Entity Framework to query the database of my company. I have an ASP.NET MVC project and as of now, I have established a connection to the company's principal server database. That has given me access to all the tables and I created a separate class Library containing all the corresponding POCOs(generated automatically).
In the tutorial I was following they say to use "enable-migrations" to have the database updated with the model.
So does that mean that if I were to modify the models in my project, that would have a direct effect on the database? Since I am new to this project I do not want to do anything stupid, like altering the database. For now I just want to query the database and retrieve information, then use that information to show more or less information on a web page.
EDIT: Just as an example, I would like to show a difference between the model generated by EF and what my real table looks like. I have a table Web_Profils that contain and ID, a ProfileName and an Order (int). This DB has no primary keys or foreign keys. If there are relations, they are defined through new tables. But when EF generates all my classes, it adds ICollections, for example in Web_Profils, I have a.o virtual ICollection<Web_User_joint_Profils>Web_User_joint_Profils which is not present in the actual table, it just seems to be the relation that EF has deduced(it is the relation between Users and Profiles present in the table Web_User_joint_Profils). Now, will doing a migration affect my tables just because EF has added these collections in my model?
I've also read that it is possible to deactivate migrations using :
Database.SetInitializer(new ContextInitializerNone<YourDbContext>());
Any thoughts?
If you update your model, you need to add a migration to your project and update your database with that migration.
Unless you do those steps after updating your model, changes will not be reflected in the database.

Database First Entity Framework

I am developing a web-based system using .NET MVC and Entity Framework, from a legacy system. I will keep the legacy database and only develop the application, so I will create entity classes using database first approach.
My concern is, in the entity classes, I will be adding attributes such as filter attributes. And I may add some extra fields there as well. Will the database be updated automatically? I actually don't want to update the database at all. I only want extra stuff stay with the entity class only.
You can easily create your database first and then start working on the backend side of your application as you would do it in an "Code first" approach.
I'd recommend reading this article, as you might get all your answers cleared with some examples: Entity framework
First, when adding additional properties in your entity classes you will want to mark them for EF to ignore using either the [NotMapped] attribute or in your DbContext class calling .Ignore on the property. Not Mapped Attribute
Second, in terms of EF changing your database you can do a couple of things.
1. Ensure the account that is updating data does not have Create,Alter,etc permissions in the environment
2. Use a null database initializer at the beginning of your application. Database.SetInitializer(null); Setting the initializer to null tells EF not to make any sort of changes to the database. Turn off DB Initializer
Maybe you should consider using partial classes.
I find editing anything in EF quite hard.
EF Classes from your DB are all :
public partial myClass(){
public string myDBProperty;
}
Which means you are able to create a second class in the same namespace like :
public partial myClass(){
public string myOwnProperty;
}

Sharing the Users table between an IdentityDbContext, and a main application DbContext

My application (built in MVC5/EF6) needs to use a single database with two schemas:
identity: To store all the AspNet identity tables for users and roles.
application: To store all my general application tables.
I want to use a separate DbContext for each schema, with the identity one being created with the Microsoft.AspNet.Identity.EntityFramework.IdentityDbContext<ApplicationUser> helper class, and the main application one being created in code with code first. The reason for having two DbContexts like this is so I can put the main application context in a separate assembly and use it in other related projects without having to reference Asp.Net.
However, I want to reference a table in the application schema/context with a foreign key that I want to add to the identity.AspNetUsers table, along with some other extra fields. I then want to create a Users entity in the main context that maps to the identity.AspNetUsers table.
For example, I want an application.Tenants table of which identity.AspNetUsers has a foreign key to, so that I can have many users belonging to a single tenant.
All this is fine I think and will work with no problems, except when it comes to creating the database, and possibly any migrations that affect that table, as I'll have two DbContext's trying to create the same table.
Can I mark a table within OnModelCreating as "do not create", and if so how do I add the foreign key constraint? If not then how do I handle this? I don't think what I'm trying to do is unreasonable. I just want to avoid having two "Users" tables linked with an implied foreign key (i.e. with no actual foreign key constraint).
Why exactly do you want to use two separate DbContexts? It would be easier to have a single context for both ASP.NET identity data and your business entities:
public class DatabaseContext : IdentityDbContext<UserInfo>
{
public virtual DbSet<Entity> Entities { get; set; } // Your business entities
public DatabaseContext()
: base("name=DatabaseContext")
{
}
}
Notice that the DatabaseContext inherits from the IdentityDbContext<UserInfo>.
There are some trade-offs with this approach: for example, your data access layer should reference Microsoft.AspNet.Identity.Core and Microsoft.AspNet.Identity.EntityFramework; however, having a single database context in your project makes things much easier if you are using dependency injection or Entity Framework migrations.

How to test views using Entity Framework?

We work with a database that isn't ours to manage. We defined some views on it so that our code (C# with Entity Framework) can simply map to these views. These views will be given to the database owners later on. They will implement them so that we can use them.
During testing, we mock that database. We used Entity Framework Tools on a backup of the database, to generate a DbContext of it. We create it each time when running tests. Is this even the way to go?
During testing we would like to insert data in some tables, and read the results out of the related views. We do this to test the views as well as the C# code that will act upon it (there is non trivial logic in those views).
What is your opinion on this? Shouldn't we recreate the mock-database each time but use a static one with the views already defined? Should we define the views in C# so that they are created on the database? Is our approach completely wrong? How do others tackel similar problems?
"During testing, we mock that database...."
In EF version 6 or later you can also mock DBContext.
"During testing we would like to insert..."
Do you have the source code of the inherited DBContext? My recommendation to handle the views just like tables. Create a class for it(Entity) and in your applicationDBContext just map the View like a normal table.
public DbSet<ImAView> ImAViews { get; set; }
With database migration you can modifiy your view with normal T-SQL Script.
"What is your opinion on this? Shouldn't"
If you are testing the application (also data access layer in version 6) you can mock everything. Do not use database creation this will make your test very slow and is some cases the tests will be depends on other tests.
IF you want to test the database it self or migration or some bulk opeations then you have to create a database (you can do everything in SQL Server without C#) and feed it with data.

Categories