Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
223 views
in Technique[技术] by (71.8m points)

dapper - How to Insert/Update an entity when entity type is not known at compile time?

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);

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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.

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

Again, there is no way for ORM to know that your object is PersonEntity. You have mapped PersonEntity and passing in an 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.

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.

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...