【发布时间】:2017-04-25 11:09:44
【问题描述】:
我是 EntityFramework 和 WCF 的初学者,所以我还不知道一切是如何工作的,所以我会尽力解释我的情况..
我有 WCF 服务,它使用带有 EntityFramework 的数据库,并且我设法让它正常工作,例如:
using (var entities = new databaseEntities())
{
// Check if there is 0 rows, then just add the new row.
int count = entities.Table1.Where(i => i.Name == name).Count();
if (count < 1)
{
var newEntry = new Table1
{
Name = name,
InsertDate = DateTime.Now,
CreatedBy = createdBy,
Comment = comment,
Active = true
};
entities.Table1.Add(newEntry);
entities.SaveChanges();
}
}
当我有不止一张桌子并且我想决定使用哪一张时,问题就来了。这些表基本相同,因此将使用相同的操作,所以我想为所有表使用一个函数(这样我可以避免重复代码)。但我似乎无法理解如何我可以在运行时更改表格,例如通过开关/案例。
例如:
// A function that gets the type of the table I want to access
void WriteToSomeTable(int type)
{
switch (type)
{
case 0:
//The table to update is Table1
break;
case 1:
//The table to update is Table2
break;
}
}
如果我想获取具有给定名称的所有条目的计数
int count = entities.Table1.Where(i => i.Name == "somename").Count();
如何在运行时确定“entities.Table1”? 我可以制作变量:
System.Data.Entity.DbSet<Table1> firstTable = entities.Table1;
System.Data.Entity.DbSet<Table2> secondTable = entities.Table2;
所以我认为使用列表我可以设置一个 int 索引;使用 switch/case 设置为不同的值,然后使用
int count = list[index].Where(i => i.Name == "somename").Count();
但我无法将它们添加到列表中,因为它们是不同的类型
// entity.Table1 is
System.Data.Entity.DbSet<Table1>
// and entity.Table2 is
System.Data.Entity.DbSet<Table2>
ArrayList 也不会删除它,因为如果我尝试使用 ArrayList 中的对象,则没有“.Where”函数。
我也尝试使用 System.Data.Entity.Dbset,但要使用“.Where”函数,我需要使用 .Cast() 函数,但我无法将所需的“TEntity”存储到变量中(或者我可以吗?)。例如:
System.Data.Entity.DbSet firstTable = entity.Table1
Type t = firstTable.GetType();
int count = firstTable.Cast<t>().Where(i => i.Name == "somename").Count();//doesn't work
//This, however works:
int count = firstTable.Cast<Table1>().Where(i => i.Name == "somename").Count();
我希望我对我的问题有所了解 :) 希望有人有一个想法,如何解决这个问题,因为我已经与这个问题斗争了很长时间,而我想出的唯一解决方案就是拥有除了“entity.Table”部分之外,在每个开关/案例中使用完全相同的代码进行单独的函数调用。而且必须多次编写同一组代码并不是一个很好的解决方案:(
【问题讨论】:
标签: c# entity-framework wcf dbset