从表格中删除

时间:2018-10-08 08:03:06

标签: c# entity-framework console-application

我有一个旧的C#控制台应用程序,目前正在升级以首先使用Entity Framework(最新版本)代码。

我将在数据库中创建20多个表。

我的一种方法是

static void DeleteModelInDb(Model pdModel, ExporterContext db) {
    string[] tables = new string[] { "PD_COLUMN", "PD_COLUMN_EXTENDED", "PD_COLUMNRULE", "PD_COLUMNSOURCE", "PD_DB_PACKAGE", "PD_DB_PACKAGE_PROC_PARAMETER", "PD_DB_PACKAGE_PROCEDURE", "PD_DB_PACKAGE_TYPE", "PD_DB_PACKAGE_VARIABLE", "PD_DIAGRAM", "PD_DIAGRAM_TABLE", "PD_DOMAIN", "PD_DOMAIN_VALUES", "PD_INDEX", "PD_INDEX_COLUMN", "PD_JOIN", "PD_MODEL", "PD_MODEL_EXTENDED", "PD_MODEL_CHANGES", "PD_MODELSOURCE", "PD_PACKAGE", "PD_REFERENCE", "PD_RULE", "PD_TABLE", "PD_TABLE_EXTENDED", "PD_TABLE_CHANGES", "PD_TABLE_KEY", "PD_TABLE_KEY_COLUMN", "PD_TABLESOURCE", "PD_VIEW", "PD_VIEWCOLUMN", "PD_VIEWSOURCE" };

    SqlConnection con = new SqlConnection("definition of con...");
    con.Open();
    SqlCommand com = con.CreateCommand();
    foreach (string table in tables)
    {
        com.CommandText = "DELETE FROM " + table + " WHERE MODEL_CODE = '" + pdModel.Code + "'";
        com.ExecuteNonQuery();
    }
    com.Dispose();
}

我想使用Entity框架做类似的事情。但是我不想为每个表都写这个删除代码。

var x = (from y in db.PdColumn
         where y.ModelCode == pdModel.Code
         select y).FirstOrDefault();
db.PdColumn.Remove(x);
db.SaveChanges();

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:0)

您应该能够通过使所有相关实体实现具有ModelCode属性的接口,然后对删除代码进行抽象,然后制定一个通用的删除方法(我假设ModelCode在下面是字符串类型):

interface IEntityWithCode {
   string ModelCode {get;}
}

void DeleteFromDbSet<T>(DBSet<T> dbset, string modelcode) where T: IEntityWithCode {
  var x = (from y in dbset
           where y.ModelCode == modelcode
           select y).FirstOrDefault();
  dbset.Remove(x);
}

由于C#不支持类的变量,所以我认为您不能在不依赖讨厌的反射hack的情况下,在新DeleteModelInDb方法中循环遍历dbset列表,因此它必须看起来像这样

void DeleteModelInDb(YourDbContext context, string modelcode) {
  DeleteFromDbSet(context.SomeTable, modelcode);
  DeleteFromDbSet(context.SomeOtherTable, modelcode);
  //and so on
}

(免责声明:由于我没有EF核心设置方便的ATM,因此代码未经过测试)