.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
david stephan
Gaurav Pal
Post New Web Links

[C#] Database ".mdf" already exists. Choose a different database name.

Posted By:      Posted Date: August 28, 2010    Points: 0   Category :Sql Server
Hi all, it's all day long that i'm fighting with this problem. And i'm getting quite upset! SHORT VERSION Why when i call DataContex.CreateDatabase() does SQLExpress 2008 say that the file already exist even if the file is completly wiped form the DISK!?!   LONG VERSION So, what i'm trying to do is damn simple. I'm developing a simple web application. To do that i've built a DBML file to use with LINQ. For development purpose i'd like to create a local DB. So here my code: string connectionString = ConfigurationManager.ConnectionStrings["PermissionsDatabase"].ConnectionString; Response.Write(connectionString); using (PermissionDataContext dataContext = new PermissionDataContext(connectionString)) { if (!dataContext.DatabaseExists()) { dataContext.CreateDatabase(); } }   And in the web.config the connection strin is: Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Projects\AccessControl\WebSite\App_Data\permissions.mdf;Integrated Security=True;User Instance=True When the CreateDatabase() is called i get that Exception. Where the ____ do SQLServer keeps track of that file?! Why if the database already exists the DatabaseExists() return false?!   Moreover if i use this connection string: Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\permissions.mdf;Integrated Security=True;User Instance=True

View Complete Post

More Related Resource Links

C# How to check prammatically if null value exists in database table (using stored procedure)?


How to programattically check if null value exists in database table (using stored procedure)?

I know it's possble in the Query Analyzer (see last SQL query batch statements)?

But how can I pass null value as parameter to the database stored procedure programattically using C#?

Although I can check for empty column (the following code passes string.Empty as parameter but how to pass null value?), I cannot check for null value in the following code snippet:

SQL Queries:

USE [master]

IF EXISTS (SELECT name FROM sys.databases WHERE name = 'ExampleDatabase')
DROP DATABASE [ExampleDatabase];

CREATE DATABASE [ExampleDatabase];

USE [ExampleDatabase];

DROP TABLE dbo.ExampleTable;

IsActive BIT,


SSIS Database Transfer Error - "Role Exists" even though DB is being overwritten in task.



Can't get over this error, and net searches reveal other postings similiar, but no answers.

SSIS database transfer task (with overwrite) from SQL 2k source to SQL 2k5 destination fails with:


Error: The Execute method on the task returned error code 0x80131500 (ERROR : errorCode=-1073548784 description=Executing the query "CREATE ROLE [RFRSH_USER] " failed with the following error: "User, group, or role 'RFRSH_USER' already exists in the current database.". Possible failure reasons: Problems with the query, "ResultSet" property not set correctly, parameters not set correctly, or connection not established correctly.  helpFile= helpContext=0 idofInterfaceWithError={8BDFE893-E9D8-4D23-9739-DA807BCDC2AC}). The Execute method must succeed, and indicate the result using an "out" parameter.

The error seems the same regardless if the destination DB exists or not!

Anyone have a solution?




Check if DataBase Exists


I have the following function coding in VB 2010 but it always returns a value of false.  Is there something wrong with my SQL code to check if a database exists?

 Public Function CheckDBExists(ByVal ConnString As String, ByVal databasename As String) As Boolean

        Dim exists As Byte = 0

        Dim conn As SqlConnection = New SqlConnection(ConnString)

        Dim cmd As SqlCommand = New SqlCommand("SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'" & databasename & "')", conn)


        exists = CByte(cmd.ExecuteScalar())


        Return CBool(exists)

    End Function

Dennis in Longview

Check if record exists in mssql database c# code


Hello everyone!

I coded this page a while back, but I'm thinking there must be a better way to do this.  What I want to do is check real-time if various records exist in my database from a function in my C# code.  What I've done is added a sqldatabase onto my page, as well as a gridview.  Here is what I have done to verify if a record exists.

public bool RecordExists(string gName, DateTime gDate)
        // Set default to false
        bool returnBool = false;
        SqlDataSourceEvents.SelectCommand = "SELECT ID, StartTime, EndTime, EventName, UserID, Details FROM EventTable WHERE (DATEPART(day, StartTime) = DATEPART(day, '" + gDate.ToString() + "')) AND (UserID='" + gName + "')";

        for (int i = 0; i < GridViewEvents.Rows.Count; i++)
            if (DateTime.Parse(GridViewEvents.Rows[i].Cells[0].Text) == gDate)
                if (GridViewEvents.Rows[i].Cells[2].Text == gName)
                    returnBool = true;
        // Return SqlDataSourceEvents to original state
        SqlDataSourceEvents.SelectCommand = "SELECT ID, StartTime, EndTime, EventName, UserID, Details FROM EventTable WHERE (DATEPART(month, StartTime) = 

Copy Database Wizard: Cannot choose databases, checkboxes are missing



I try to move databases from one SQL 2008 R2 to another SQL 2008 R2 Server with the copy database wizard.
On the page where I should choose the databases to move or copy the checkboxes are missing. The databases are listed but no way to choose one of them.

I searched a lot but did not find out what the reason could be for this.
Any hints are appreciated, thank you!

Multiple database support with Entity Framework

One of the features introduced in Entity Framework is being database independent. Which mean each database provider can support Entity Framework by implementing its provider.

This feature allows you build applications independent from the underplaying database provider. In this post I'm going to show how to build an application that support multiple databases using same conceptual model made by Entity Framework.

Export Visio Database Table Names to Excel

If you use the Enterprise Architect edition of Microsoft Visio for data modeling regularly, then there is a good chance that at some point you've wanted to export just the table names into Excel. You might want to do this to map logical ERD entities to physical data model tables, track project status by entity, or track overlap between database versions.

MS SQL Server: Disconnect Users From Database - Kill User Session

If you ever wanted to restore your database from a SQL backup file (.bak), but there are still users connected to your database, the backup operation will fail causing the error: Exclusive access could not be obtained because the database is in use.

Publishing SQL Server Database using Publishing Wizard : Tips & Tricks

We can use SQL Server Publishing Wizard to deploy our local Database to remote hosting server/production server.This feature is available in SQL Server 2008/VWD 2008.

Below is the complete step by step guide of this process.

Adding Rows in GridView without using a Database

This article describes on how to add rows in GridView without using a database. Basically the GridView will be populated with data based on the values entered in the TextBox on Button Click and retain the GridView data on post back.

Adding Multiple Columns and Rows in GridView without using a Database

This article describes on how to add multiple columns and rows in GridView without using a database. Basically the GridView will be populated with data based on the values entered in each TextBoxes on Button Click and retain the GridView data on post back.

ASP.NET Database Tutorial

This tutorial will show you how to display data using the .NET GridView Control, ASP.NET 2.0 and VB.NET

The GridView control is a powerful tool and is simple to implement.

First, you will need to import the System.Data.SqlClient namespace.

Connestion string create any database server

This links important to how to create connection string to any data base sever.

SQL Server Database Transaction

A transaction is a group of SQL commands executed together as a single component of work to be accomplished. If all of these commands succeed, then a transaction is committed - the changes to the data are made final. If any of the commands within a transaction fail, then the entire transaction is cancelled, or in SQL Server terms, the transaction will be rolled back.

Transactions are one of the things that keep your data safe, but they're not necessarily easy to understand. Here's some help:

Database Export Wizard for ASP.net and SQL Server

A step wizard for ASP.net to export database objects to CSV, TXT, HTML, XML, or SQL. it guides users through a few simple steps to choose a database object (table, view, or query), select columns, and export the data in any of the standard formats CSV, HTML, XML, or SQL.

Reading and Writing Images From a Windows Mobile Database using UltraLite 10(C#)

Periodically I get a request for information on how to read and write binary data to a database running on Windows Mobile. If you search the Internet you can typically find examples that are available on Windows Desktops or allow you to read and write to a local file system. The problem is that it can take a bit of work to get this code to work on Windows Mobile accessing a database.

Ultimately you might be asking, why would I want to store and image in a database? Well in an environment where you synchronizing data between a local mobile database and a consolidated (central) database this can be extremely useful. Imagine if an insurance adjuster went to an accident scene, took a picture of a damaged car, loaded it into his Windows Mobile database and then replicated that image up to the Insurance headquarters for approval. All of this could be done in a very short period of time when using images in the database. Another good example might be a doctor who was waiting for a patient chart to become available. If you could store the image in a database this chart could be sent down to the doctor's device once it became available.

For this article I am not going to get into how to synchronize the images to and from a remote and central database as this is typically fairly straightforward when using a data synchronization technologies like MobiLink

Store and Display Images from MS Access Database Using C#

There is only the difference of coding syntax to stream the binary data of image content type to upload it into MS Access Database using C#/VB in ASP.Net 2.0

Namespaces required:-
using System.Data.OleDb;

OleDb is used to connect the web site forms with MS Access Database using Microsoft.Jet.OLEDB.4.0
ASP.NetWindows Application  .NET Framework  C#  VB.Net  ADO.Net  
Sql Server  SharePoint  Silverlight  Others  All   

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend