I have been using the model-first approach for about two weeks now and it works great. I also used the "Generate Database from Model" option, which results in a DDL being generated, which in turn is an SQL script that I run to create the database. If I add entities to my model and update the DDL it does not add an alter statement to entities that already exist, so if I were to run the script again it deletes previous tables and recreates them and deletes any data. Is there any way I can prevent this? Or do it differently? Or change my approach?
Try Entity Designer Database Generation Power Pack. http://blogs.msdn.com/b/adonet/archive/2010/02/08/entity-designer-database-generation-power-pack.aspx
Not really the DDL approach has two problems, and one is not really fixable:
As you found out it creates / recreates a database. No maintenance.
More important: It is stupid. As in: not smart. It can only use a very small but most common subset of what one can do in SQL Server, so it basically is only feasible for the most simplistic databases.
If you do not beliee the second point, read up the complete DDL for SQL Server in the documentation and be surprised how many things one can do for not so common settings. All are transparent to the SQL UQuery side. And the vast majority of advanced features are not usable in EF4 DDL.
Related
I am having an issue with my website(ASP.NET, c#, SQL, Code-first Entity Framework).
I have a project with an attached SQL database generated from code first entity framework.
Now I have imported another SQL database using model first database which looks almost same but the table and column names are different.
So now I would like to write data to two databases at the same time with just one click from my web application.
The newly attached database will be a backup and we should write data to both databases at the same time.
Any suggestions would be highly appreciated.
Thanks
As others have suggested, you need to do the mapping yourself, but one thing I would like to add, you may need to wrap your SaveChanges() into a transaction, you may find steps here: https://msdn.microsoft.com/en-us/data/dn456843.aspx
I have an c#.net windows based application that uses a database in Microsoft SQL Server 2008. During deployment for very first time to our client(s), we create a copy of our database and deploy it on client(s) remote server along with the UI application. The client database can be on version SQL Server 2005 and higher.
During times the UI application and associated database has gone lots of changes. Since this is a thick client application the client(s) database is not sync with our latest database and unfortunately no one ever made notes of all the changes done. So my challenges are as follows:
How to find any missing columns on database table in Client's Database as compared to my Database? if any?
How to find any missing Primary/Unique Constraints on database table in Client's Database as compared to my Database? if any?
How to find any missing Indexes on database table that exist in Client's Database as compared to my Database? if any?
Please keep in mind the client(s) database size may ranges from 10-100GB, so i cannot plan to just drop all client tables and recreate it.
You can use Data-tier applications. It's built-in feature of SQL Server, so you don't need to use any extra tools.
You can extract data-tier application from your database (in SSMS right-click -> Tasks -> Extract data-tier application) to a DACPAC file, copy the file to the client's server and use it to upgrade the DB there (or generate update script).
It also integrates nicely with SQL Server Data Tools.
For this task, you need a software that compare SQL database. Just like there is a lot of software to compare text, there is a lot to compare database.
Personally, I use AdoptSQLDiff, but there is a bunch. RedGate has developed one also and I know others exists. Just type SQL Database compare in google to find them. You probably can have the job done with the trial period.
These softwares show you which tables was added, deleted or changed. It does the same for views, indexes, triggers, Stored Procedures, User Defined Functions, Constraints. More importantly, those tools generate script to push modifications into the target database. Very handy, but have a look at the script generated, it sometime messes it up by deleting data, but it can be fixed very easily.
There is also the option to compare data in a specific table if you need to.
Here is a screen shot of the interface of another so you know what it's look like.
With SQLServer Management Studio, you can try selecting a database and then Task->Generate Script, selecting appropriate options.
Do the same thing for the 2 db you want to compare. You will get two text files you can compare with a text file software comparer.
Comparison will highlight difference in the db structure.
Not the best way to do it, of course. But it can be a start. If the two dbs are not too different, you should be able to handle the differences
Better option, use some db comparer software. They are meant to compare db structure, constraint indexes and so on. Never used any of them, so cannot give any advice on that
If it is one time thing use any diff tool for DB, VS2010+ has a build in one, allows you to get difference for schema and data in two different files.
If you want to solve problem of your development process, you have wide range of options to implement versioning for data base.
If you are using EF - use Migrations, can't beat that.
If you are only on SQL Server and never looking at other RDBMS, check DAC ( Data-Tier applications, mentioned by Jakub)
Otherwise take a look at more generic solutions, among them I would reccomend you to take a look at DB.UP and if python code is good for you , check Alembic, it allow you to write your migrations using really nice python API.
if nothing works for you, create snapshot of current db schema and start doing differential scripts that you can use with self written tool or DB.UP
I am not sure if this can help, but who knows.
So is there any way to restore the server database on your local environment? If the answer is yes, you can try to join system views for each database and compare them?
I propose something like this(was a quick solution, so please sorry for formatting and other common stuff).
USE [master]
GO
SELECT
LocalDataBaseTable.name AS TableName,
LocalDataBaseTableColumns.name AS [Column],
LocalDataBaseTypes.name AS DataType,
LocalDataBaseTableColumns.max_length,
LocalDataBaseTableColumns.[precision]
INTO #tmpLocalInfo
FROM LocalTable.sys.columns as LocalDataBaseTableColumns
INNER JOIN LocalTable.sys.tables AS LocalDataBaseTable
ON LocalDataBaseTableColumns.object_id = LocalDataBaseTable.object_id
INNER JOIN LocalTable.sys.types AS LocalDataBaseTypes
ON LocalDataBaseTypes.user_type_id = LocalDataBaseTableColumns.user_type_id
SELECT
ServerDataBaseTable.name AS TableName,
ServerDataBaseTableColumns.name AS [Column],
ServerDataBaseTypes.name AS DataType,
ServerDataBaseTableColumns.max_length,
ServerDataBaseTableColumns.[precision]
INTO #tmpServerInfo
FROM ServerTable.sys.columns as ServerDataBaseTableColumns
INNER JOIN ServerTable.sys.tables AS ServerDataBaseTable
ON ServerDataBaseTableColumns.object_id = ServerDataBaseTable.object_id
INNER JOIN ServerTable.sys.types AS ServerDataBaseTypes
ON ServerDataBaseTypes.user_type_id = ServerDataBaseTableColumns.user_type_id
SELECT
#tmpServerInfo.*
FROM #tmpLocalInfo
RIGHT OUTER JOIN #tmpServerInfo
ON #tmpLocalInfo.TableName = #tmpServerInfo.TableName COLLATE DATABASE_DEFAULT
AND #tmpLocalInfo.[Column] = #tmpServerInfo.[Column] COLLATE DATABASE_DEFAULT
WHERE #tmpLocalInfo.[Column] IS NULL
DROP TABLE #tmpLocalInfo
DROP TABLE #tmpServerInfo
This will return all information about missed columns in your local database. The idea is to investigate 'sys' views and to find out if there any suitable solution for you.
You can use this simple script, which show you differences between tables, views, indexes etc.
Compalex is a free lightweight script to compare two database schemas. It
supports MySQL, MS SQL Server and PostgreSQL.
or look at this question Compare two MySQL databases. This question about comparing two MySQL schemas, but some of listed tools supports MSSQL or have MSSQL version (for example http://www.liquibase.org/).
Another answer What is best tool to compare two SQL Server databases (schema and data)?
I would like to add new module (project) to my solution and to use entity framework code first only for subest of my database tables. I'm using ADO.NET with stored procedures in other modules. I plan to split tables from db in the future, but for now it is not possible (tables have no relations to other tables but are used by old modules) I'm not sure if it is good practise to do it in this way and I would like to ask for help.
is it possible to use EF code first for subset of the tables of my DB?
how to initialize these tables with code first? I found only solutions to drop whole
db if model doesn't match and recreate new DB. I need drop and recreate only
tables that are used in my project
is it good practise to use more approaches of the db access to one db?
do you see some problems in this approach? Now I see problem with concurency and data consistency ( if old module will operate with this tables in another approach )
Thank you.
1) Yes, it is. On one of our projects, we had database with store procedures which we migrated to use EF. But not at once. It had taken some time so we used Store procedures whit ADO.NET as well as EF together.
2) I must say I'm not sure about this. We had database already created with only few changes. But you could created tables by yourself.
3) I think better would be to call stored procedures from EF and use it on whole projects if you need them. But using both, ADO.NET and EF is ok, if you have reasons.
4) Why it would be problem if you will use transactions?
People suggest creating database table dynamically (or, in run-time) should be avoided, with the saying that it is bad practice and will be hard to maintain.
I don't see the reason why, and I don't see difference between creating table and any another SQL query/statement such as SELECT or INSERT. I wrote apps that create, delete and modify database and tables in run time, and so far I do not see any performance issues.
Can anyone explane the cons of creating database and tables in run-time?
Tables are much more complex entities than rows and managing table creation is much more complex than an insert which has to abide by an existing model, the table. True, a table create statement is a standard SQL operation but depending on creating them dynamically smacks of a bad design decisions.
Now, if you just create one or two and that's it, or an entire database dynamically, or from a script once, that might be ok. But if you depend on having to create more and more tables to handle your data you will also need to join more and more and query more and more. One very serious issue I encountered with an app that made use of dynamic table creation is that a single SQL Server query can only involve 255 tables. It's a built-in constraint. (And that's SQL Server, not CE.) It only took a few weeks in production for this limit to be reached resulting in a nonfunctioning application.
And if you get into editing the tables, e.g. adding/dropping columns, then your maintenance headache gets even worse. There's also the matter of binding your db data to your app's logic. Another issue is upgrading production databases. This would really be a challenge if a db had been growing with objects dynamically and you suddenly needed to update the model.
When you need to store data in such a dynamic manner the standard practice is to make use of EAV models. You have fixed tables and your data is added dynamically as rows so your schema does not have to change. There are drawbacks of course but it's generally thought of as better practice.
KMC ,
Remember the following points
What if you want to add or remove a column , you many need to change in the code and compile it agian
what if the database location changes
Developers who are not very good at database can make changes , if you create the schema at the backend , DBA's can take care of it.
If you get any performance issues , it may get tough to debug.
You will need to be a little clearer about what you mean by "creating tables".
One reason to not allow the application to control table creation and deletion is that this is a task that should be handled only by an administrator. You don't want normal users to have the ability to delete whole tables.
Temporary tables ar a different story, and you may need to create temporary tables as part of your queries, but your basic database structure should be managed only by someone with the rights to do so.
sometimes, creating tables dynamically is not the best option security-wise (Google SQL injection), and it would be better using stored procedures and have your insert or update operations occur at the database level by executing the stored procedures in code.
I am absolutely new to the .NET world, and started with C# on friday. I have some experience with database apps, though.
We will go with LINQ-to-SQL for a medium scale project. I am used to generating my schema from classes and keep track of changes with subversion and equivalents to Ruby's Migrations. There obviously is no easy way to do this with LINQ itself.
So I thought of generating the schema (and do some data access) with Castle Project's ActiveRecord and use Migrator.NET Tarantino or dbdeploy.net for the schema updates. (Any suggestions for this?)
My main question is: How do I verify that my LINQ classes still match the database schema? Does LINQ throw exceptions if the schema does not match? Can I iterate over all the LINQ classes and invoke some verify method?
I already found that sqlmetal is the way to regenerate the classes.
PS: We will use SQL Server (2008 or 2005).
This tool will help sync them, but I'm unsure if it'll show differences...may be of some use though. (:
EDIT: As KristoferA said in his comment, it does support comparisons (: - thanks KristoferA.
As for the:
I am used to generating my schema
from classes and keep track of changes
I just added a DDL generation feature to Huagati DBML/EDMX Tools (ver 1.47, released today). It can generate DDL diff scripts in case you have added things to your Linq-to-SQL designer but not yet added them to the database.