views:

580

answers:

2

I have a project with a formidable data access layer using LinqtoSQL for just about anything touching our databases. I needed to build a helper class that bridges some common crud operations from CLSA objects to LinqToSql ones. Everything has been operating swimmingly until I needed to do a truncate on a table and all I had were “delete” methods.

Uh-oh. A quick search reveals that some people are using YourContext.ExecuteCommand(), which is nice and all, but I am trying to go “t-sql-less” as much as possible these days.

Is there a LINQ way to perform a truncate on a table? Or am I just clueless?

+3  A: 

This is not possible without doing a custom T-SQL query. Doing a .Delete() and SubmitChanges afterwords would, as you probably already know, result in a DELETE statement.

Of course you could create a stored procedure that truncates the table, and then call the procedure from LINQ, but that isn't really what you're looking for I believe.

Mark S. Rasmussen
Yeah. That's the most OOP approach but it still requires the passing of a string variable. I have a table called "Page" which needs to be "Pages" in the C#/ASPNET world for obvious reasons. So truncating that table requires the dev to know "page" == the entity Pages.
Ian Patrick Hughes
If you made a sproc, you could get around that by mapping a "Pages"-ish C# sproc name to the actual sproc in the database that did the truncate. If you have to go the TSQL way then you could add the method to the generated partial LINQ classes (depending on how you make them) and hide it that way.
Mark S. Rasmussen
Aaaaaaaaaaaaaaaaah. Now we're on the express train to NerdVille. Population: Us. I like it. I mean, basically they would pass in an entity object and I'd cast the type to a string and pass it into the sproc that maps the class to table name. Nice.
Ian Patrick Hughes
+2  A: 

You can do something like this:

yourDataContext.ExecuteCommand("TRUNCATE TABLE YourTable");
CMS
Right. That's what I mentioned in the question. I am trying to be TSQL free at last!!! :)
Ian Patrick Hughes