【问题标题】:How to choose database table to update druing runtime如何在运行时选择要更新的数据库表
【发布时间】:2020-03-17 11:22:35
【问题描述】:

我正在尝试根据 FactoryBuilder 在我的代码中返回的对象来更新我的数据库中的不同表。 我想使用 InstrumentFactory,它在运行时给我对象/仪器,然后我用(更新信息)做一些操作

var tmpInstrument = InstrumentFactory.MakeInstrument(nameOfTable);
//old code was.....  var tmpInstrument = new SuperTable();

但是,当我以后想更新我的数据库时,我不知道如何对其进行编码,因为 InstrumentFactory 的对象是在运行时根据“nameOfTable”设置的。我想根据 tmpInstrument 可能是什么对象来更新不同的表。

                    if (tmpInstrument is SuperTable)
                    {
                       _context.SupterTable.Add((ObjectCast)tmpInstrument);

                       _context.SaveChanges();

                    }

有什么好办法说更新 _context.ThisParticularTable 或 _context.AnotherObjectTable 取决于 tmpSplitInfo 是哪个对象 并且还删除了 if 语句和强制转换。

谢谢

【问题讨论】:

    标签: c# sql database runtime builder


    【解决方案1】:

    您似乎正在尝试确定tmpSplitInfo 是否属于SuperTable 类型,所以我建议您查看is keyword

    if(tmpSplitinfo is SuperTable)
    {
       _context.SuperTable.Add(tmpInstrument);
       _context.SaveChanges();
    }
    

    【讨论】:

    • 这就解决了第一个问题。在更新数据库时,似乎没有强制转换就无法完成,_context.SuperTable.Add((SuperTable)tmpInstrument);有什么办法可以避免铸造?
    • @Johan Maybe - 更完整的代码示例可能会有所帮助。我不确定 tmpSplitInfo 和 tmpInstrument 之间的关系是什么,在这里。如果您只是想避开这种特殊的强制转换语法,您也许可以利用"is 'Type pattern'" 来利用if(tmpInstrument is SuperTable ti) 之类的东西
    • 你是对的 cmhoequist,有一些拼写错误,tmpSplitInto 应该是 tmpInstrument。我昨天收到了一些输入,现在已经使用:_context.Set(tmpInstrument.GetType()).Add(tmpInstrument);
    【解决方案2】:

    这就是我一直在寻找的(感谢 Elias)。

    _context.Set(tmpInstrument.GetType()).Add(tmpInstrument);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-19
      • 1970-01-01
      • 1970-01-01
      • 2017-06-22
      • 2013-07-16
      • 1970-01-01
      相关资源
      最近更新 更多