How to initialize System.Data.Entity.Migrations.DbMigrationsConfiguration.Seed() [closed] - c#

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
How to make AddOrUpdate() generating update t-sql?
How to make AddOrUpdate() generating t-sql sent to sql server in sequence?
How to create multiple columns 'reference' index in EF6?
come on

This is to gather all the solutions of pitfall I encountered on initializing
System.Data.Entity.Migrations.DbMigrationsConfiguration.Seed().
I am T-SQL master, but I'm not EF master due to I always on the MS SQL side.
I found DbContext.AddOrUpdate(new instance(){}) didn't generate the update T-sql, and throw exception when EF encountered inserting the repeat row error in sql server.
Here is the solution gave by roelant-m:
migrationdbsett addorupdate trouble
When I solved the AddOrUpdate(new Instance(){}) inserting same row problem, I encountered the EF optimizing problem, yeah, he is so smart that optimize all the AddOrUpdate( new instance()) in method Seed(). and then he throw exceptions.
Due to the Initializing database must be in sequence (some table has referenced the other tables.)
Here is the solution gave by endi zhupani:
how to make the addorupdate run in order in dbmigrationconfiguration derived
When I solved the initializing AddOrUpdate(new Instance(){}) in sequence, I encountered the multiple column 'references' index, some element of the index are navigation property.
Here is solution gave by sampath:
how to create multi columns reference index join index in csharp model

Related

How do I Intentionally cause a database validation error on insert [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I am trying to cause a database validation error when inserting into (or editing) the database to test the try/catch
C# is too smart and catches my type casting errors.
Try inserting a value that doesn't fit into a column (a string 10 characters long in a varchar(2)),
reference a foreign key that does not exist,
a null value in a column that doesn't accept nulls,
try connecting to the database with the wrong password/user combination.
Without any sql/c# code it's hard to know how you have things setup
EDIT- answer in comments:
"do you have any identity fields? try inserting a value that already exists into that column"

I can't drop table in SQL even after tried all the methods I found on the Internet [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I can't drop an SQL table even after I tried everything I found on the web. I actually want to delete and recreate an SQL table after clicking the "SAVE" button in my C# app (a simple SQL database editor). It works fine for tables with just data (no special rules like primary keys, forbidden nulls, etc.) but for more complicated ones I call a delete function (DROP TABLE table1), then a CREATE TABLE table1 ..., it throws an error "There is already an object named 'table1' in the database". Can anyone help? Thanks in advance!
i think your issue the tables didn't drop. since there is a relationship between tables.
So if the table you doping is a FK to other table , it will not go through.
try DeleteRule = Cascade.

C# / SQL Server : MVVM insert data into multiple tables [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I work on a small project just to get to understand the mvvm model in C# better.
I work with a Microsoft SQL Server database with three tables: customer, location and address.
Every customer can have one or more locations, and every location has a specific address.
My current thought how to accomplish this:
First insert the customer.
To insert the location, get the highest customer_id and insert the location with the max(customer_id)
Then, to insert the address, get the max(location_id) and insert the address, with the location id
Is there a better way to do this?
I haven't found any tutorial with an example of inserting data into more than one table, especially not using SQL Server.
And my next problem is: what should I bind to my TextBoxes, so that I can insert the content of it?
I thought about having a save button. This button would then execute a method, where I insert the data from the bound TextBoxes. Should I do this with commands, instead of writing a method?
Thanks already!
Sql server has a OUTPUT clause which you can use
something like
INSERT INTO MyTable VALUES({CustomerName})
OUTPUT INSERTED.ID
then you can store the inserted customer's actual ID and do the rest inserts in separate queries.
As for your second question yes you should do it with Command binding to a method in your View model
The most advisable for your situation is to use a transaction.
Example.- https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqltransaction(v=vs.110).aspx

Bulk insert using AddRange in Entity framework [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I am adding multiple entities in the database using AddRange in Entity Framework:
foreach (string tagNumber in notPresent)
{
element = new TagMaster { Name = Guid.NewGuid().ToString(), IsActive = true };
element.TagCollections.Add(new TagCollection { TagNumber = tagNumber });
newTagMasters.Add(element);
}
dbContext.TagMasters.AddRange(newTagMasters);
dbContext.SaveChanges();
What I was expecting is that by adding the complete collection in context using AddRange method, there would be a single query that will be sent to database. But to my surprise, I see multiple insert statements for each record to be inserted.
Any Insights?
The problem you are running in is that sadly the entity framework commands know NO bulk inserts. Instead they generate 1 statement per line that you want to insert.
There is no workaround to this.
The only possiblity to get 1 single statement that does all the inserts is to use specific classes or libraries. As example here SqlBulkCopy which needs no external lib to be downloaded to work.
Here a link to the msdn site:
https://msdn.microsoft.com/de-de/library/system.data.sqlclient.sqlbulkcopy(v=vs.110).aspx
The usage is quite easy. You only give the constructor your connection (after opening it beforehand!) and tell it what it shall write to teh server and what the destination table name is. Then you only need to close the connection afterwards again.
sqlcon.Open();
using (SqlBulkCopy sqlBulkCopyVariable= new SqlBulkCopy(sqlcon))
{
sqlBulkCopyVariable.BulkCopyTimeout = 600; // 10 minutes timeout
sqlBulkCopyVariable.DestinationTableName = "targetTableName";
sqlBulkCopyVariable.WriteToServer(MyData);
}
sqlcon.Close();
The WriteToServer takes DataTable, DataReader or even arrays of DataRow. The exact implementation there would depend on how you want to give the data to it. So far from my personal experience: That class is quite fast and generates only 1 single statement. BUT it is only there for SqlClients. Thus if you have a different client you need to look up which class or external library would be best fitting for you.
I am afraid insertions through Linq is not optimized as you would expect. It does that by multiple insert statements as you observed. You could instead bypass Linq in those cases and use the bulk copying alternatives instead (ie: for MS SQL server use SqlBulkCopy class, for postgreSQL use Copy etc).

Whats Better: Check if table exists or always fire create statement [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
Is it OK to always fire the create statements rather than checking them like
SELECT * FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME = 'my_table_name'
in SQL SERVER CE and C#.
Because irrespective of the approach, there is always a single query that will be fired. Isnt it ???
I am using trasaction for creating all tables. So, I am sure if there is one table present, then definitely all of them are created.
So if i use the same transaction, then the transaction will fail right at the very first create table statement: But is this good performance wise???
Check if table exists or always fire create statement
If the table already exists in database, you will get an exception.
You can check for table existence, delete and then create it, something like:
if OBJECT_ID('dbo.my_table_name', 'U') IS NOT NULL
DROP TABLE dbo.my_table_name;
--and then
CREATE TABLE ....
If you mean try to create the table and look for an exception, then no. Exceptions are expensive, and if they are not handled properly can terminate your program unexpectedly.
The best practice would be to check for the table's existence.

Categories