Can I programatically delete all entities in EDMX mode?
I have a method to delete all my tables.
I'd like to know if I can:
(1) Iterate over the meta data in the model to accomplish the same thing?
(2) Reset the Identity Insert counts along the way?
Note: I don't want to delete the entire database, just all the tables.
Here's the code I want to convert to a generic loop:
public void Delete() {
using (var db = this.DirectAgentsEntities)
{
db.StartingBalances.DeleteObjects(db.StartingBalances);
...
db.RecordSourceTypes.开发者_如何学运维DeleteObjects(db.RecordSourceTypes);
db.SaveChanges();
}
}
static class Extensions {
static public void DeleteObjects<TEntity>(this ObjectSet<TEntity> set, IEnumerable<TEntity> data) where TEntity : class {
foreach (var entity in data)
set.DeleteObject(entity);
}
}
It may be simpler to:
- drop the database
- recreate the database
- create the tables
The edmx file is just xml, so you could loop through it, then for each table you find:
- Delete from Tablename
- DBCC CHECKIDENT (Tablename, reseed, 0)
Just write a stored procedure and import it to your edmx. That will be the fastest way with entity framework.
I took the suggestion of Shiraz, and came up with a complete answer to my question as an imported SProc and a T4 template:
SProc:
ALTER procedure dbo.DeleteTable
(
@tableName varchar(500)
)
AS
declare @sql varchar(1000)
set @sql = 'delete from ' + @tableName
exec (@sql)
return
T4 Template:
<#@ template debug="true" hostSpecific="true" #>
<#@ output extension=".cs" #>
<#@ Assembly Name="System.Core.dll" #>
<#@ Assembly Name="System.Xml.dll" #>
<#@ Assembly Name="System.Xml.Linq.dll" #>
<#@ Assembly Name="System.Windows.Forms.dll" #>
<#@ import namespace="System" #>
<#@ import namespace="System.IO" #>
<#@ import namespace="System.Diagnostics" #>
<#@ import namespace="System.Linq" #>
<#@ import namespace="System.Xml.Linq" #>
<#@ import namespace="System.Collections" #>
<#@ import namespace="System.Collections.Generic" #>
<#
string ns = "EomApp1.Formss.AB2.Model";
string cn = "Util";
string edmxFile = "\\ABModel.edmx";
string inputContent = System.IO.File.ReadAllText(System.IO.Path.GetDirectoryName(this.Host.TemplateFile) + edmxFile);
#>
namespace <#=ns#>
{
static public class <#=cn#>
{
<#DeleteTablesCodeGen(inputContent);#>
}
}
<#+
void DeleteTablesCodeGen(string input)
{
XNamespace edmxNS = "http://schemas.microsoft.com/ado/2008/10/edmx";
XNamespace ssdlNS ="http://schemas.microsoft.com/ado/2009/02/edm/ssdl";
System.Xml.Linq.XDocument xd = System.Xml.Linq.XDocument.Parse(input);
var tables =
from c in xd.Root
.Element(edmxNS + "Runtime")
.Element(edmxNS + "StorageModels")
.Element(ssdlNS + "Schema")
.Element(ssdlNS + "EntityContainer")
.Elements(ssdlNS + "EntitySet")
select new
{
Name = c.Attribute("Name").Value,
EntitySet = c
};
foreach (var table in tables)
{
#>
static public void Delete<#=table.Name#>(DirectAgentsEntities model)
{
model.DeleteTable("<#=table.Name#>");
}
<#+
}
}
#>
精彩评论