Click here to Skip to main content
15,896,207 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
I am trying to Truncate table before populating it with data. I already have all the tables and can populate it with information. This is how I set up Entity using .edmx Diagram I choose [Update Model From Database ...] then select the table I need and it sets every up for me.

Then in the code I use this:

C#
MyEntities myE = new MyEntities();

SomeEntityTable table = new SomeEntityTable();
table.someFieldName1 = "Value1";
table.someFiledName2 = "Value2";
...

myE.Add(table);
myE.SaveChanges();


Could somebody help me figure out how to add a line before I use this table to truncate all the data in a table prior to running this code. I know I need to get a context then run Truncate Table but not sure how.

Thanks.
Posted
Updated 23-Oct-13 8:28am
v4

Okay here is what I did.

C#
MyEntities myE = new MyEntities();

// This will clear your table and your index will start at 1.
var objCtx = ((System.Data.Entity.Infrastructure.IObjectContextAdapter)myE).ObjectContext;
objCtx.ExecuteStoreCommand("Truncate table SomeEntityTable");
 
SomeEntityTable table = new SomeEntityTable();
table.someFieldName1 = "Value1";
table.someFiledName2 = "Value2";
...
 
myE.Add(table);
myE.SaveChanges();
 
Share this answer
 
Comments
Sampath Lokuge 24-Oct-13 1:52am    
+5 for put your final code snippet :)
You can use below mentioned code for that (this is a sample)

C#
var objCtx = ((System.Data.Entity.Infrastructure.IObjectContextAdapter)dataDb).ObjectContext;
objCtx.ExecuteStoreCommand("TRUNCATE TABLE [Table]");



for more info : Entity Framework. Delete all rows in table

OR

Truncate

I hope this will help to you.
 
Share this answer
 
Check this sample application:

Entity Framework for Beginners[^]
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900