C# 如何选择数据库表更新druing运行时
我试图根据FactoryBuilder在代码中返回的对象更新数据库中的不同表。 我想使用InstrumentFactory,它在运行时为我提供对象/工具,然后我使用它执行一些操作(更新信息) 但是,当我以后想要更新我的DB时,我不知道如何对它进行编码,因为InstrumentFactory在运行时根据“nameOfTable”设置了对象。我想根据tmpInstrument可能是什么对象更新不同的表C# 如何选择数据库表更新druing运行时,c#,sql,database,runtime,builder,C#,Sql,Database,Runtime,Builder,我试图根据FactoryBuilder在代码中返回的对象更新数据库中的不同表。 我想使用InstrumentFactory,它在运行时为我提供对象/工具,然后我使用它执行一些操作(更新信息) 但是,当我以后想要更新我的DB时,我不知道如何对它进行编码,因为InstrumentFactory在运行时根据“nameOfTable”设置了对象。我想根据tmpInstrument可能是什么对象更新不同的表 if (tmpInstrument is SuperTab
if (tmpInstrument is SuperTable)
{
_context.SupterTable.Add((ObjectCast)tmpInstrument);
_context.SaveChanges();
}
根据tmpSplitInfo是哪个对象,有没有合适的方式来表示update _context.thispiculartable或_context.AnotherObjectTable
并删除if语句和强制转换。
谢谢看起来您正在尝试确定
tmpSplitInfo
是否属于SuperTable
类型,因此我建议您查看:
这就是我要找的(谢谢Elias)
这就解决了第一个问题。在更新数据库时,似乎不强制转换,_context.SuperTable.Add((SuperTable)tmpInstrument)就无法完成;有什么办法可以避免这种情况吗?@Johan也许-一个更完整的代码示例可能会有所帮助。在这里,我不太确定tmpSplitInfo和tmpInstrument之间的关系是什么。如果您只是想避开这种特殊的强制转换语法,您可能能够利用类似于
If(tmpInstrument是SuperTable ti)
的功能,您是对的,cmhoequist,有一些拼写错误,tmpSplitInto应该是tmpInstrument。我昨天收到了一些输入,现在使用了:_context.Set(tmpinstructure.GetType()).Add(tmpinstructure);
if (tmpInstrument is SuperTable)
{
_context.SupterTable.Add((ObjectCast)tmpInstrument);
_context.SaveChanges();
}
if(tmpSplitinfo is SuperTable)
{
_context.SuperTable.Add(tmpInstrument);
_context.SaveChanges();
}
_context.Set(tmpInstrument.GetType()).Add(tmpInstrument);