在编译时未知实体类型时,如何插入/更新实体? [英] How to Insert/Update an entity when entity type is not known at compile time?

查看:51
本文介绍了在编译时未知实体类型时,如何插入/更新实体?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Dapper.FastCrud对 Insert / Update 方法使用通用类型参数.当在编译时知道实体类型时,这很好用.但是,当在编译时不知道实体类型时,似乎没有办法使用Dapper.FastCrud对这些代码进行 Insert / Update 实体.例如:

The Dapper.FastCrud uses the generic type argument for Insert/Update methods. This works well when the entity types are known at compile time. However, when the entity types are not known at compile time, there seems to be no way to use Dapper.FastCrud to Insert/Update these entities. For example:

object person = new PersonEntity();
connnection.Insert(person);

尽管已向 OrmConfiguration 注册了 PersonEntity 映射,但此方法不起作用.

This does not work despite having PersonEntity mappings registered with the OrmConfiguration.

有关如何启用此类方案的任何想法?

Any ideas on how to enable such scenarios? Are there any non-generic versions available for Insert/Update methods?

推荐答案

Dapper(通常是任何ORM)的扩展都支持自动查询生成.为此,他们需要知道要针对其生成查询的表名.他们通过查看传入的实体的通用类型并将其与完成的映射相关联来了解它.

Extensions of Dapper (or generally any ORM) support auto-query-generation. To do it, they need to know the table name against which the query should be generated. They know it by looking at generic type of entity passed in and relating it with mapping done.

您正在尝试插入 object 类型.ORM无法知道应该为哪个表生成查询.这就是为什么您无法做的事情.

You are attempting to insert an object type. There is no way for ORM to know for which table the query should be generated. That is why, what you are attempting to do is not possible.

尽管已向 OrmConfiguration

同样,ORM无法知道您的 object PersonEntity .您已经映射了 PersonEntity 并传递了 object .

Again, there is no way for ORM to know that your object is PersonEntity. You have mapped PersonEntity and passing in an object.

要使其实现,请投射具有完全实体的 object :

To make it happen, cast an object with exact entity:

connnection.Insert(person as PersonEntity);

插入时,您的代码知道您要插入的内容.只需强制转换为特定类型即可解决该问题.

While Insert, your code know what you are inserting. Simply casting to specific type should resolve the issue.

文档所述,您可以使用该工具的SQL Builder功能.我从未使用过该工具包,因此不知道这是否对您有帮助.只是建议看看文档.

As mentioned in the document, you can use SQL Builder feature of tool. I never used the toolkit so I do not know if this will help you; just suggesting looking at documentation.

一个有用的SQL构建器和语句格式化程序,即使您不需要此库的CRUD功能也可以使用.

A useful SQL builder and statement formatter which can be used even if you don't need the CRUD features of this library.

这篇关于在编译时未知实体类型时,如何插入/更新实体?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆